概述
ValueAnimator只能对数值做动画计算。如果想对哪个控件操作,需要监听动画过程,然后在监听中对控件操作。这样使用起来相比补间动画而言就相对比较麻烦。为了能让动画直接与对应控件相关联,以使我们从监听动画过程中解放出来,谷歌的开发人员在ValueAnimator的基础上,又派生了一个类ObjectAnimator;由于ObjectAnimator是派生自 ValueAnimator 的,所以 ValueAnimator 中所能使用的方法,在ObjectAnimator中都可以正常使用。但 ObjectAnimator 也重写了几个方法,比如 ofInt(),ofFloat()等。
下面以ObjectAnimator 的ofFloat方法为例:
public static ObjectAnimator ofFloat(Object target, String propertyName, float... values)
target用于指定这个动画要操作的是哪个控件
propertyName用于指定这个动画要操作这个控件的哪个属性
values是可变长参数,这个就跟 ValueAnimator 中的可变长参数的意义一样了,就是指这个属性值是从哪变到哪。
要注意的地方:
ObjectAnimator 做动画,并不是根据控件 xml 中的属性来改变的,而是通过指定属性所对应的set方法来改变的。比如,我们指定改变rotation的属性值,ObjectAnimator在做动画时就会到指定控件(TextView)中去找对应的setRotation()方法来改变控件中对应的值,在使用的过程中药特别注意以下几点:
- 要使用 ObjectAnimator 来构造对画,要操作的控件中,必须存在对应的属性的 set 方法
- 系统先根据属性值拼装成对应的 set 函数的名字,比如这里的 rotation 的拼装方法就是将属性的第一个字母强制大写后,与 set 拼接,所以就是 setRotation 。然后通过反射找到对应控件的 setRotation(float rotation)函数。
- set 方法的命名必须以骆驼拼写法命名,即 set 后每个单词首字母大写,其余字母小写,即类似于 setPropertyName 所对应的属性为 propertyName。
ObjectAnimator 动画流程:
示例Demo:
layout/activity_object_animator_demo.xml
<?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"
tools:context="com.makesky.studydemo01.Animator.ObjectAnimator.ObjectAnimatorDemoActivity"
android:orientation="vertical"
android:padding="10dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/bt_start_anim01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动Alpha动画"/>
<ImageView
android:id="@+id/iv_image01"
android:layout_width="200dp"