Kotlin实现propertyAnimator

26 篇文章 0 订阅
2 篇文章 0 订阅

项目要用到一个动画效果,正好最近在看kotlin相关的东西,用kotlin做了个Demo

import android.animation.ObjectAnimator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_anim.*

class AnimActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_anim)
        item2.setOnClickListener{
            animate()
        }
    }

    fun animate(){
        ObjectAnimator.ofFloat(item1,"translationY",item1.translationY,-item1.height.toFloat()).setDuration(500).start()
        ObjectAnimator.ofFloat(item2,"translationY",item2.translationY,-item1.height.toFloat()).setDuration(500).start()
        ObjectAnimator.ofFloat(item3,"translationY",item3.translationY,2*item4.height.toFloat()).setDuration(500).start()
        ObjectAnimator.ofFloat(item4,"translationY",item4.translationY,2*item4.height.toFloat()).setDuration(500).start()
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/item1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#0000ff" />

    <TextView
        android:id="@+id/item2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ff0000" />

    <TextView
        android:id="@+id/item3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#00ff00" />

    <TextView
        android:id="@+id/item4"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ffff00" />
</LinearLayout>

代码很简单,实现了一个平移动画,在点击一个控件时实现所有控件分别向上和向下平移的效果。

使用kotlin中需要注意的点:
1.直接使用布局中的id,需要import
2.setOnClickListener的语法格式

主要关注点还是动画吧:
这里用到了ObjectAnimator使用的时候,ofXXX方法的propertyName这个参数,是View的某一成员变量,而且有对应的setter和getter方法。
ObjectAnimator本身是通过ValueAnimator来实现动画的,ValueAnimator能在指定范围内连续改变变量的值,利用这一点来实现属性动画。ObjectAnimator通过propertyName属性指定需要ValueAnimator改变的属性值,类似的属性值有top,bottom,left,right,height,x,y等

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值