来完成这个Android动画系列,之前写了View Animation和Drawable Animation,接下来讲解三种动画中的最后一种,Property Animation,这也是Android动画中最强大的一部分,同时也是相对最复杂的一部分。
Property Animation与Value Animation的区别
Property Animation翻译为属性动画,从Android3.0开始引入,相比与View Animation,官方更推荐开发者使用Property Animation。以下先讲解View Animation和Property Animation的区别:
1,View Animation只能对界面上可见的组件进行修改,而Property Animation除此之外还能修改一些不是界面上可见的组件,比如修改一个float类型的值。(刚开始我看到这点也觉得奇怪,不过确实它就是如此,后面会讲解怎么应用它到界面动画中)
2,View Animation通过动画效果改变一个组件时,其实只是在屏幕上另一个地方绘制,而组件的响应位置还是没改变,比如一个在屏幕左侧的按钮,通过View Animation移动到右侧,虽然在屏幕上看到按钮到了右侧了,但是你还是需要点击左侧原来的位置,按钮才会响应。
3,Proerty Animation能修改很多View Animation不能修改的View控件的属性,比如背景颜色。
接下来主要讲解Property Animation的用法,包含了ValueAnimator,ObjectAnimator和AnimatorSet.
ValueAnimator
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);animation.setDuration(1000);animation.start();animation.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { System.out.println("onAnimationUpdate = " + animation.getAnimatedValue()); //可以在这里更新UI }});从这个例子看以看出,让一个浮点数进行Property Animator的变化,有什么作用呢?你只需要使用addUpdateListener,然后再监听的onAnimationUpdate中,使用getAnimatedValue()获取更新值,然后你将该值使用于UI,并刷新界面。这样一来,浮点型的Property Animator的与界面动画效果就联系起来了。
ObjectAnimator
ObjectAnimator anim = ObjectAnimator.ofFloat(foo, "alpha", 0f, 1f);anim.setDuration(1000);anim.start()
以上ObjectAnimator.ofFloat的四个参数,分别是作用的对象,以及作用的属性,起始值,目标值。其中作用的属性,必须在作用的对象中有一个setter方法。用ObjectAnimator,会自动将更新值应用于构造方法中声明的属性。
ObjectAnimator colorAnim = ObjectAnimator.ofInt(tv, "textColor",0xff008271, Color.RED);colorAnim.setDuration(4000);colorAnim.setEvaluator(new ArgbEvaluator());colorAnim.setRepeatCount(100);colorAnim.start();
AnimatorSet
AnimatorSet bouncer = new AnimatorSet();bouncer.play(bounceAnim).before(squashAnim1);bouncer.play(squashAnim1).with(squashAnim2);bouncer.play(squashAnim1).with(stretchAnim1);bouncer.play(squashAnim1).with(stretchAnim2);bouncer.play(bounceBackAnim).after(stretchAnim2);ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);fadeAnim.setDuration(250);AnimatorSet animatorSet = new AnimatorSet();animatorSet.play(bouncer).before(fadeAnim);animatorSet.start();
Animation Listeners
- onAnimationStart()
- onAnimationEnd()
- onAnimationRepeat()
- onAnimationCancel() 动画取消时会回调该方法,也会回调onAnimationEnd()
TypeEvaluator的原理
布局变化动画
- APPEARING::新元素(child view)出现的动画
- CHANGE_APPEARING:由于新元素出现,引起其他元素变化的动画
- DISAPPEARING:移除元素的消失动画
- CHANGE_DISAPPEARING:由于元素被移除,引起其他元素变化的动画。
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/verticalContainer" android:animateLayoutChanges="true" />
这里不列出例子了,可以参考APIDemo中的几个例子