Kotlin实现propertyAnimator

来源:互联网 发布:windows禁止启动程序 编辑:程序博客网 时间:2024/06/07 17:24

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

import android.animation.ObjectAnimatorimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport 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等