上一篇给大家讲了属性动画中的ValueAnimator,如果大家细细的观察研究就会发现ValueAnimator的不足之处就是只能对数值对动画计算。假设一下如果我们要想对哪个控件操作,需要监听动画过程,在监听中对控件操作,如果用ValueAnimator来操作的话相比补间动画而言就相对比较麻烦和复杂。 那我们又想用属性动画又想实现这样的效果应该怎么做呢?这就引出了我们今天要讲的属性动画的另外一种ObjectAnimator,大家先看一下官方的介绍:
由于ObjectAnimator是派生自ValueAnimator的,所以ValueAnimator中所能使用的方法,在ObjectAnimator中都可以正常使用并且对其中的某些方法进行重写,只要大家对ValueAnimator熟悉了,那么ObjectAnimator用起来的时候就很容易理解了。
先给大家看一下效果图:
一个简单的平移动画,但是用的却是ObjectAnimator。看下代码:
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", 0, 100,0);
animator.setDuration(3000);
animator.setInterpolator(new BounceInterpolator());
animator.start();
是不是灰常的简单?
我们在看下方法的参数都是什么意思:
public static ObjectAnimator ofFloat (Object target, String propertyName, float... values)
Added in API level 11
Constructs and returns an ObjectAnimator that animates between float values. A single value implies that that value is the one being animated to.
Two values imply starting and ending values. More than two values imply a starting value, values to animate through along the way,
and an ending value (these values will be distributed evenly across the duration of the animation).
Parameters
target The object whose property is to be animated. This object should have a public method on it called setName(),
where name is the value of the propertyName parameter.
propertyName The name of the property being animated.
values A set of values that the animation will animate between over time.
Returns
An ObjectAnimator object that is set up to animate between the given values.
以上是谷歌官方给出的解释,具体的中文意思也简单。- 第一个参数用于指定这个动画要操作的是哪个控件
- 第二个参数用于指定这个动画要操作这个控件的哪个属性
- 第三个参数是可变长参数,这个就跟ValueAnimator中的可变长参数的意义一样了,就是指这个属性值是从哪变到哪。像我们上面的代码中指定的就是将view的translationX属性从0变到100再变到0;
//1、透明度:alpha
public void setAlpha(float alpha)
//2、旋转度数:rotation、rotationX、rotationY
public void setRotation(float rotation)
public void setRotationX(float rotationX)
public void setRotationY(float rotationY)
//3、平移:translationX、translationY
public void setTranslationX(float translationX)
public void setTranslationY(float translationY)
//缩放:scaleX、scaleY
public void setScaleX(float scaleX)
public void setScaleY(float scaleY)
//背景颜色
public void setBackgroundColor(@ColorInt int color) 对应的字段是BackgroundColor
所以第二个参数的值就是我上面标红的,在选择的时候要注意,可不是想写什么就写什么的。
到这的时候基本用法大家可能会了,大家会有疑问补间动画可以同时进行集中不同的动画,那么属性动画可以吗?这个你能想到的谷歌同样会想到的,当然是可行的,大家看下效果:
有没有发现控件一遍在平移一边在进行背景颜色的变换。看下代码:
ObjectAnimator animator1 = ObjectAnimator.ofFloat(view, "translationX", 0, 100,0);
ObjectAnimator animator2 = ObjectAnimator.ofInt(view, "BackgroundColor", 0xffff00ff,0xffffff00, 0xffff00ff);
AnimatorSet animator = new AnimatorSet();
animator.setDuration(3000);
animator.playTogether(animator1,animator2);
animator.setInterpolator(new BounceInterpolator());
animator.start();
补间动画有个AnimationSet属性动画有个AnimatorSet,他们的用法大同小异。到这就差不多要结束了,其实大家细心地话就会发现ObjectAnimator ofPropertyValuesHolder(Object target,PropertyValuesHolder... values)的方法,其用法大家可以自行研究下,里面很多东西可以自定义的,大家对动画有兴趣的话可以深入的研究。