Android动画机制全解析

导论

本文着重讲解Android3.0后推出的属性动画框架Property Animation——Animator。

产生原因

        3.0之前已有的动画框架——Animation存在一些局限性, Animation框架定义了透明度,旋转,缩放和位移几种常见的动画,而且控制的是整个View,实现原理是每次绘制视图时View所在的ViewGroup中的drawChild函数获取该View的Animation的Transformation值,然后调用canvas.concat(transformToApply.getMatrix()),通过矩阵运算完成动画帧,如果动画没有完成,继续调用invalidate()函数,启动下次绘制来驱动动画,动画过程中的帧之间间隙时间是绘制函数所消耗的时间,可能会导致动画消耗比较多的CPU资源,最重要的是,动画改变的只是显示,并不能相应事件。

        而在Animator框架中使用最多的是AnimatorSet和ObjectAnimator配合,使用ObjectAnimator进行更精细化控制,只控制一个对象的一个属性值,多个ObjectAnimator组合到AnimatorSet形成一个动画。而且ObjectAnimator能够自动驱动,可以调用setFrameDelay(longframeDelay)设置动画帧之间的间隙时间,调整帧率,减少动画过程中频繁绘制界面,而在不影响动画效果的前提下减少CPU资源消耗。因此,Anroid推出的强大的属性动画框架,基本可以实现所有的动画效果。

强大的原因

        因为属性动画框架操作的是真实的属性值,直接变化了对象的属性,因此可以很灵活的实现各种效果,而不局限于以前的4种动画效果。

ObjectAnimator

        ObjectAnimator是属性动画框架中最重要的实行类,创建一个ObjectAnimator只需通过他的静态工厂类直接返回一个ObjectAnimator对象。传的参数包括一个对象和对象的属性名字,但这个属性必须有get和set函数,内部会通过java反射机制来调用set函数修改对象属性值。还包括属性的初始值,最终值,还可以调用setInterpolator设置曲线函数。

ObjectAnimator实例

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ObjectAnimator  
  2. .ofFloat(view, "rotationX"0.0F, 360.0F)  
  3. .setDuration(1000)  
  4. .start();  

        这个例子很简单,针对view的属性rotationX进行持续时间为1000ms的0到360的角度变换。
PS: 可操纵的属性参数:x/y;scaleX/scaleY;rotationX/ rotationY;transitionX/ transitionY等等。

PS:X是View最终的位置、translationX为最终位置与布局时初始位置的差。所以若就用translationX即为在原来基础上移动多少,X为最终多少。getX()的值为getLeft()与getTranslationX()的和。


1. translationX和translationY:这两个属性作为一种增量来控制着View对象从它布局容器的左上角坐标开始的位置。

2. rotation、rotationX和rotationY:这三个属性控制View对象围绕支点进行2D和3D旋转。

3. scaleX和scaleY:这两个属性控制着View对象围绕它的支点进行2D缩放。

4. pivotX和pivotY:这两个属性控制着View对象的支点位置,围绕这个支点进行旋转和缩放变换处理。默认情况下,该支点的位置就是View对象的中心点。

5. x和y:这是两个简单实用的属性,它描述了View对象在它的容器中的最终位置,它是最初的左上角坐标和translationX和translationY值的累计和。

6. alpha:它表示View对象的alpha透明度。默认值是1(不透明),0代表完全透明(不可见)。


动画绘制过程的监听

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. animator.addUpdateListener(new AnimatorUpdateListener() {  
  2.             @Override  
  3.             public void onAnimationUpdate(ValueAnimator arg0) {  
  4.             }  
  5.         });  

该方法用来监听动画绘制过程中的每一帧的改变,通过这个方法,我们可以在动画重绘的过程中,实现自己的逻辑。

同时修改多个属性值

当然这个可以使用Animationset来实现,这里我们使用一种取巧的方法来实现:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ObjectAnimator anim = ObjectAnimator.ofFloat(view, "xxx"1.0F, 0.0F)  
  2.                 .setDuration(500);  
  3.         anim.start();  
  4.         anim.addUpdateListener(new AnimatorUpdateListener() {  
  5.             @Override  
  6.             public void onAnimationUpdate(ValueAnimator animation) {  
  7.                 floatcVal = (Float) animation.getAnimatedValue();  
  8.                 view.setAlpha(cVal);  
  9.                 view.setScaleX(cVal);  
  10.                 view.setScaleY(cVal);  
  11.             }  
  12.         });  

我们可以监听一个并不存在的属性,而在监听动画更新的方法中,去修改view的属性,监听一个不存在的属性的原因就是,我们只需要动画的变化值,通过这个值,我们自己来实现要修改的效果,实际上,更直接的方法,就是使用ValueAnimator来实现,其实ObjectAnimator就是 ValueAnimator的子类 ,这个在下面会具体讲到。

为不具有get/set方法的属性提供修改方法

        Google在应用层为我们提供了2种解决方法,一种是通过自己写一个包装类,来为该属性提供get/set方法,还有一种是通过ValueAnimator来实现,ValueAnimator的方法我们在下面会具体讲解,这里讲解下如何使用自定义的包装类来给属性提供get/set方法。

包装类

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. private static class WrapperView {  
  2.             private View mTarget;  
  3.   
  4.             public WrapperView(View target) {  
  5.                 mTarget = target;  
  6.             }  
  7.   
  8.             public int getWidth() {  
  9.                 return mTarget.getLayoutParams().width;  
  10.             }  
  11.   
  12.             public void setWidth(int width) {  
  13.                 mTarget.getLayoutParams().width = width;  
  14.                 mTarget.requestLayout();  
  15.             }  
  16.         }  

使用方法:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ViewWrapper wrapper = new ViewWrapper(mButton);  
  2. ObjectAnimator.ofInt(wrapper, "width"500).setDuration(5000).start();  

这样就间接给他加上了get/set方法,从而可以修改其属性实现动画效果。

多动画效果的另一种实现方法——propertyValuesHolder

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public void propertyValuesHolder(View view) {  
  2.         PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f,  
  3.                 0f, 1f);  
  4.         PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f,  
  5.                 0, 1f);  
  6.         PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f,  
  7.                 0, 1f);  
  8.         ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ)  
  9.                 .setDuration(1000).start();  
  10.     }  

ValueAnimator

        说简单点,ValueAnimator就是一个数值产生器,他本身不作用于任何一个对象,但是可以对产生的值进行动画处理。
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ValueAnimator animator = ValueAnimator.ofFloat(0100);  
  2.         animator.setTarget(view);  
  3.         animator.setDuration(1000).start();  
  4.         animator.addUpdateListener(new AnimatorUpdateListener() {  
  5.             @Override  
  6.             public void onAnimationUpdate(ValueAnimator animation) {  
  7.                 Float value = (Float) animation.getAnimatedValue();  
  8.                 imageView.setTranslationY(value);  
  9.             }  
  10.         });  

        通过这个动画我们可以发现,和我们在上面提供的使用ObjectAnimator的方法很像,的确,我前面说这个才是专业的写法,就是这个原因,动画生成的原理就是通过差值器计算出来的一定规律变化的数值作用到对象上来实现对象效果的变化,因此我们可以使用ObjectAnimator来生成这些数,然后在动画重绘的监听中,完成自己的效果。
        ValueAnimator是计算动画过程中变化的值,包含动画的开始值,结束值,持续时间等属性。但并没有把这些计算出来的值应用到具体的对象上面,所以也不会有什么的动画显示出来。要把计算出来的值应用到对象上,必须为ValueAnimator注册一个监听器ValueAnimator.AnimatorUpdateListener,该监听器负责更新对象的属性值。在实现这个监听器的时候,可以通过getAnimatedValue()的方法来获取当前帧的值。
        ValueAnimator封装了一个TimeInterpolator,TimeInterpolator定义了属性值在开始值与结束值之间的插值方法。ValueAnimator还封装了一个TypeAnimator,根据开始、结束值与TimeIniterpolator计算得到的值计算出属性值。ValueAnimator根据动画已进行的时间跟动画总时间(duration)的比计算出一个时间因子(0~1),然后根据TimeInterpolator计算出另一个因子,最后TypeAnimator通过这个因子计算出属性值,例如在10ms时(total 40ms):
首先计算出时间因子,即经过的时间百分比:t=10ms/40ms=0.25
经插值计算(inteplator)后的插值因子:大约为0.15,如果使用了AccelerateDecelerateInterpolator,计算公式为(input即为时间因子):
(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
最后根据TypeEvaluator计算出在10ms时的属性值:0.15*(40-0)=6pixel。如果使用TypeEvaluator为FloatEvaluator,计算方法为 :
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public Float evaluate(float fraction, Number startValue, Number endValue) {  
  2.         float startFloat = startValue.floatValue();  
  3.         return startFloat + fraction * (endValue.floatValue() - startFloat);  
  4.     }  

参数分别为上一步的插值因子,开始值与结束值。

ValueAnimator与ObjectAnimator实例

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.example.animtest;  
  2.   
  3. import android.animation.TypeEvaluator;  
  4. import android.animation.ValueAnimator;  
  5. import android.animation.ValueAnimator.AnimatorUpdateListener;  
  6. import android.app.Activity;  
  7. import android.graphics.PointF;  
  8. import android.os.Bundle;  
  9. import android.util.DisplayMetrics;  
  10. import android.view.View;  
  11. import android.view.Window;  
  12. import android.view.WindowManager;  
  13. import android.view.animation.BounceInterpolator;  
  14. import android.view.animation.LinearInterpolator;  
  15. import android.widget.ImageView;  
  16.   
  17. public class AnimateFreeFall extends Activity {  
  18.   
  19.     private int screenHeight;  
  20.     private int screenWidth;  
  21.     private ImageView imageView;  
  22.   
  23.     @Override  
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  27.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
  28.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  29.         setContentView(R.layout.animate_free_fall);  
  30.         DisplayMetrics metrics = new DisplayMetrics();  
  31.         getWindowManager().getDefaultDisplay().getMetrics(metrics);  
  32.         screenHeight = metrics.heightPixels;  
  33.         screenWidth = metrics.widthPixels;  
  34.   
  35.         imageView = (ImageView) findViewById(R.id.im);  
  36.     }  
  37.   
  38.     public void clean(View view) {  
  39.         imageView.setTranslationX(0);  
  40.         imageView.setTranslationY(0);  
  41.     }  
  42.   
  43.     public void freefall(View view) {  
  44.         final ValueAnimator animator = ValueAnimator.ofFloat(0, screenHeight  
  45.                 - imageView.getHeight());  
  46.         animator.setTarget(view);  
  47.         animator.setInterpolator(new BounceInterpolator());  
  48.         animator.setDuration(1000).start();  
  49.         animator.addUpdateListener(new AnimatorUpdateListener() {  
  50.   
  51.             @Override  
  52.             public void onAnimationUpdate(ValueAnimator animation) {  
  53.                 Float value = (Float) animation.getAnimatedValue();  
  54.                 imageView.setTranslationY(value);  
  55.             }  
  56.         });  
  57.     }  
  58.   
  59.     public void parabola(View view) {  
  60.         ValueAnimator animator = ValueAnimator.ofObject(  
  61.                 new TypeEvaluator<PointF>() {  
  62.   
  63.                     @Override  
  64.                     public PointF evaluate(float fraction, PointF arg1,  
  65.                             PointF arg2) {  
  66.                         PointF p = new PointF();  
  67.                         p.x = fraction * screenWidth;  
  68.                         p.y = fraction * fraction * 0.5f * screenHeight * 4f  
  69.                                 * 0.5f;  
  70.                         return p;  
  71.                     }  
  72.                 }, new PointF(00));  
  73.         animator.setDuration(800);  
  74.         animator.setInterpolator(new LinearInterpolator());  
  75.         animator.start();  
  76.         animator.addUpdateListener(new AnimatorUpdateListener() {  
  77.   
  78.             @Override  
  79.             public void onAnimationUpdate(ValueAnimator animator) {  
  80.                 PointF p = (PointF) animator.getAnimatedValue();  
  81.                 imageView.setTranslationX(p.x);  
  82.                 imageView.setTranslationY(p.y);  
  83.             }  
  84.         });  
  85.     }  
  86. }  


        效果如下图:


        有一点需要注意的是,由于ofInt,ofFloat等无法使用,我们自定义了一个TypeValue,每次根据当前时间返回一个PointF对象,(PointF和Point的区别就是x,y的单位一个是float,一个是int point float的意思)PointF中包含了x,y的当前位置,然后在更新监听中更新。

        自定义TypeEvaluator传入的泛型可以根据自己的需求,自己设计个Bean。

动画事件的监听

        通过监听这个事件在属性的值更新时执行相应的操作,对于ValueAnimator一般要监听此事件执行相应的动作,不然Animation没意义(但是可用于计时),在ObjectAnimator(继承自ValueAnimator)中会自动更新属性,所以不必监听。在函数中会传递一个ValueAnimator参数,通过此参数的getAnimatedValue()取得当前动画属性值。
PS:根据应用动画的对象或属性的不同,可能需要在onAnimationUpdate函数中调用invalidate()函数刷新视图通过动画的各种状态,我们可以监听动画的各种状态。

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", 0.5f);  
  2.         anim.addListener(new AnimatorListener() {  
  3.             @Override  
  4.             public void onAnimationStart(Animator animation) {  
  5.             }  
  6.   
  7.             @Override  
  8.             public void onAnimationRepeat(Animator animation) {  
  9.             }  
  10.   
  11.             @Override  
  12.             public void onAnimationEnd(Animator animation) {  
  13.             }  
  14.   
  15.             @Override  
  16.             public void onAnimationCancel(Animator animation) {  
  17.             }  
  18.         });  
  19.         anim.start();  

可以看见,API提供了开始、重复、结束、取消等各种状态的监听,同时,API还提供了一种简单的监听方法,可以不用监听所有的事件:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. anim.addListener(new AnimatorListenerAdapter() {  
  2.             @Override  
  3.             public void onAnimationEnd(Animator animation) {  
  4.             }  
  5.         });  

通过AnimatorListenerAdapter来选择你需要监听的事件

动画监听的实例应用

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.example.animtest;  
  2.   
  3. import android.animation.Animator;  
  4. import android.animation.AnimatorListenerAdapter;  
  5. import android.animation.ObjectAnimator;  
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.widget.ImageView;  
  10.   
  11. public class AnimateMoveInSecond extends Activity {  
  12.   
  13.     private ImageView imageView;  
  14.   
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.animate_move_in_second);  
  19.         imageView = (ImageView) findViewById(R.id.imageView1);  
  20.     }  
  21.   
  22.     public void doit(View view) {  
  23.         ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "alpha",  
  24.                 1.0f, 0f);  
  25.         animator.setDuration(1000);  
  26.         animator.start();  
  27.         animator.addListener(new AnimatorListenerAdapter() {  
  28.   
  29.             @Override  
  30.             public void onAnimationEnd(Animator animation) {  
  31.                 super.onAnimationEnd(animation);  
  32.                 ObjectAnimator animator = ObjectAnimator.ofFloat(imageView,  
  33.                         "alpha", 0f, 1.0f);  
  34.                 animator.setDuration(1000);  
  35.                 animator.start();  
  36.                 imageView.setTranslationY(400);  
  37.             }  
  38.         });  
  39.     }  
  40. }  


效果如下图:

AnimatorSet

        AnimatorSet用于实现多个动画的协同作用。效果如下:



[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "scaleX",  
  2.                 1f, 2f);  
  3.         ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "scaleY",  
  4.                 1f, 2f);  
  5.         ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView,  
  6.                 "translationY", 0f, 500f);  
  7.         AnimatorSet set = new AnimatorSet();  
  8.         set.setDuration(1000);  
  9.         set.playTogether(animator1, animator2, animator3);  
  10.         set.start();  

AnimatorSet中有一系列的顺序控制方法:playTogether、playSequentially、animSet.play().with()、defore()、after()等。用来实现多个动画的协同工作方式。

使用xml来创建动画

        属性动画于以前的动画一样,也支持通过xml文件来创建动画,下面是一个简单的例子:
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:duration="1000"  
  4. android:propertyName="scaleX"  
  5. android:valueFrom="1.0"  
  6. android:valueTo="2.0"  
  7. android:valueType="floatType" >  
  8. </objectAnimator>  

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public void scaleX(View view)  
  2. {  
  3. // 加载动画  
  4. Animator anim = AnimatorInflater.loadAnimator(this, R.animator.scalex);  
  5. anim.setTarget(mMv);  
  6. anim.start();  
  7. }  

布局动画

         布局动画是指ViewGroup在布局时产生的动画效果

LayoutTransition动画

        通过LayoutTransition来实现容器在添加子view的时候的动画过渡效果:


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.example.animtest;  
  2.   
  3. import android.animation.Animator;  
  4. import android.animation.AnimatorListenerAdapter;  
  5. import android.animation.Keyframe;  
  6. import android.animation.LayoutTransition;  
  7. import android.animation.ObjectAnimator;  
  8. import android.animation.PropertyValuesHolder;  
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.LinearLayout;  
  15.   
  16. public class AnimateLayoutTransition extends Activity {  
  17.   
  18.     private LinearLayout ll;  
  19.     private LayoutTransition mTransition = new LayoutTransition();  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.animate_layout_transition);  
  25.   
  26.         ll = (LinearLayout) findViewById(R.id.ll);  
  27.         setupCustomAnimations();  
  28.         ll.setLayoutTransition(mTransition);  
  29.     }  
  30.   
  31.     public void add(View view) {  
  32.         final Button button = new Button(this);  
  33.         ll.addView(button);  
  34.         button.setOnClickListener(new OnClickListener() {  
  35.   
  36.             @Override  
  37.             public void onClick(View arg0) {  
  38.                 ll.removeView(button);  
  39.             }  
  40.         });  
  41.     }  
  42.   
  43.     // 生成自定义动画  
  44.     private void setupCustomAnimations() {  
  45.         // 动画:CHANGE_APPEARING  
  46.         // Changing while Adding  
  47.         PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left"01);  
  48.         PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top"01);  
  49.         PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right"0,  
  50.                 1);  
  51.         PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom",  
  52.                 01);  
  53.         PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofFloat("scaleX",  
  54.                 1f, 0f, 1f);  
  55.         PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofFloat("scaleY",  
  56.                 1f, 0f, 1f);  
  57.   
  58.         final ObjectAnimator changeIn = ObjectAnimator.ofPropertyValuesHolder(  
  59.                 this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX,  
  60.                 pvhScaleY).setDuration(  
  61.                 mTransition.getDuration(LayoutTransition.CHANGE_APPEARING));  
  62.         mTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, changeIn);  
  63.         changeIn.addListener(new AnimatorListenerAdapter() {  
  64.             public void onAnimationEnd(Animator anim) {  
  65.                 View view = (View) ((ObjectAnimator) anim).getTarget();  
  66.                 // View也支持此种动画执行方式了  
  67.                 view.setScaleX(1f);  
  68.                 view.setScaleY(1f);  
  69.             }  
  70.         });  
  71.   
  72.         // 动画:CHANGE_DISAPPEARING  
  73.         // Changing while Removing  
  74.         Keyframe kf0 = Keyframe.ofFloat(0f, 0f);  
  75.         Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);  
  76.         Keyframe kf2 = Keyframe.ofFloat(1f, 0f);  
  77.         PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe(  
  78.                 "rotation", kf0, kf1, kf2);  
  79.         final ObjectAnimator changeOut = ObjectAnimator  
  80.                 .ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight,  
  81.                         pvhBottom, pvhRotation)  
  82.                 .setDuration(  
  83.                         mTransition  
  84.                                 .getDuration(LayoutTransition.CHANGE_DISAPPEARING));  
  85.         mTransition  
  86.                 .setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changeOut);  
  87.         changeOut.addListener(new AnimatorListenerAdapter() {  
  88.             public void onAnimationEnd(Animator anim) {  
  89.                 View view = (View) ((ObjectAnimator) anim).getTarget();  
  90.                 view.setRotation(0f);  
  91.             }  
  92.         });  
  93.   
  94.         // 动画:APPEARING  
  95.         // Adding  
  96.         ObjectAnimator animIn = ObjectAnimator.ofFloat(null"rotationY", 90f,  
  97.                 0f).setDuration(  
  98.                 mTransition.getDuration(LayoutTransition.APPEARING));  
  99.         mTransition.setAnimator(LayoutTransition.APPEARING, animIn);  
  100.         animIn.addListener(new AnimatorListenerAdapter() {  
  101.             public void onAnimationEnd(Animator anim) {  
  102.                 View view = (View) ((ObjectAnimator) anim).getTarget();  
  103.                 view.setRotationY(0f);  
  104.             }  
  105.         });  
  106.   
  107.         // 动画:DISAPPEARING  
  108.         // Removing  
  109.         ObjectAnimator animOut = ObjectAnimator.ofFloat(null"rotationX", 0f,  
  110.                 90f).setDuration(  
  111.                 mTransition.getDuration(LayoutTransition.DISAPPEARING));  
  112.         mTransition.setAnimator(LayoutTransition.DISAPPEARING, animOut);  
  113.         animOut.addListener(new AnimatorListenerAdapter() {  
  114.             public void onAnimationEnd(Animator anim) {  
  115.                 View view = (View) ((ObjectAnimator) anim).getTarget();  
  116.                 view.setRotationX(0f);  
  117.             }  
  118.         });  
  119.   
  120.     }  
  121. }  

上面的例子中自定义了 LayoutTransition来修改默认的过渡动画,如果保持默认则使用系统默认的动画效果。
过渡的类型一共有四种:
LayoutTransition.APPEARING 当一个View在ViewGroup中出现时,对此View设置的动画
LayoutTransition.CHANGE_APPEARING当一个View在ViewGroup中出现时,对此View对其他View位置造成影响,对其他View设置的动画
LayoutTransition.DISAPPEARING当一个View在ViewGroup中消失时,对此View设置的动画
LayoutTransition.CHANGE_DISAPPEARING当一个View在ViewGroup中消失时,对此View对其他View位置造成影响,对其他View设置的动画
LayoutTransition.CHANGE 不是由于View出现或消失造成对其他View位置造成影响,然后对其他View设置的动画。
注意动画到底设置在谁身上,此View还是其他View。

AnimateLayoutChanges动画

        ViewGroup的xml属性中有一个默认的animateLayoutChanges属性,设置该属性,可以添加ViewGroup增加view的过渡效果:



[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:id="@+id/ll"  
  4. android:layout_width="match_parent"  
  5. android:layout_height="match_parent"  
  6. android:animateLayoutChanges="true"  
  7. android:orientation="vertical" >  
  8. <Button  
  9. android:id="@+id/button1"  
  10. android:layout_width="wrap_content"  
  11. android:layout_height="wrap_content"  
  12. android:onClick="add"  
  13. android:text="Add Button" />  
  14. </LinearLayout>  

LayoutAnimation动画

        通过设置LayoutAnimation也同样可以实现布局动画效果,实例如下:



[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.example.animtest;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.animation.LayoutAnimationController;  
  6. import android.view.animation.ScaleAnimation;  
  7. import android.widget.LinearLayout;  
  8.   
  9. public class AnimateLayoutAnimation extends Activity {  
  10.   
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.animate_layout_animation);  
  15.           
  16.         LinearLayout ll = (LinearLayout) findViewById(R.id.ll);  
  17.         ScaleAnimation sa = new ScaleAnimation(0101);  
  18.         sa.setDuration(2000);  
  19.         // 第二个参数dely : the delay by which each child's animation must be offset  
  20.         LayoutAnimationController lac = new LayoutAnimationController(sa, 0.5F);  
  21.         // 设置显示的顺序 这个必须要在dely不为0的时候才有效  
  22.         lac.setOrder(LayoutAnimationController.ORDER_NORMAL);  
  23.         ll.setLayoutAnimation(lac);  
  24.     }  
  25. }  

View的animate方法

        3.0后android对View也提供了直接作用的动画API:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. view.animate().alpha(0).y(100).setDuration(1000)  
  2.                 .withStartAction(new Runnable() {  
  3.                     @Override  
  4.                     public void run() {  
  5.                     }  
  6.                 }).withEndAction(new Runnable() {  
  7.                     @Override  
  8.                     public void run() {  
  9.                         runOnUiThread(new Runnable() {  
  10.                             @Override  
  11.                             public void run() {  
  12.                             }  
  13.                         });  
  14.                     }  
  15.                 }).start();  

Interpolators(插值器)

        插值器和估值器,是实现非线性动画的基础,了解这些东西,才能作出不一样的动画效果。所谓的插值器,就是通过一些数学物理公式,计算出一些数值,提供给动画来使用。就好比我们定义了起始值是0,结束值是100,但是这0到100具体是怎么变化的呢,这就是插值器产生的结果,线性的,就是匀速增长,加速的,就是按加速度增长。这些增加的算法公式,已经不需要我们来自己设计了,Android内置了7种插值器,基本可以满足需求,当然你也可以自定新的插值器。
AccelerateInterpolator 加速
Decelerate 减速
AccelerateDecelerateInterpolator 开始,和结尾都很慢,但是,中间加速
AnticipateInterpolator 开始向后一点,然后,往前抛
OvershootInterpolator 往前抛超过一点,然后返回来
AnticipateOvershootInterpolator 开始向后一点,往前抛过点,然后返回来 
BounceInterpolator 结束的时候弹一下
LinearInterpolator 默认 匀速

TypeEvalutors (估值器)

        根据属性的开始、结束值与TimeInterpolation计算出的因子计算出当前时间的属性值,android提供了以下几个evalutor:
IntEvaluator:属性的值类型为int;
FloatEvaluator:属性的值类型为float;
ArgbEvaluator:属性的值类型为十六进制颜色值;
TypeEvaluator:一个接口,可以通过实现该接口自定义Evaluator。
  自定义TypeEvalutor很简单,只需要实现一个方法,如FloatEvalutor的定义:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class FloatEvaluator implements TypeEvaluator {  
  2.         public Object evaluate(float fraction, Object startValue,  
  3.                 Object endValue) {  
  4.             float startFloat = ((Number) startValue).floatValue();  
  5.             return startFloat + fraction  
  6.                     * (((Number) endValue).floatValue() - startFloat);  
  7.         }  
  8.     }  

        根据动画执行的时间跟应用的Interplator,会计算出一个0~1之间的因子,即evalute函数中的fraction参数。

KeyFrame

        keyFrame是一个 时间/值 对,通过它可以定义一个在特定时间的特定状态,即关键帧,而且在两个keyFrame之间可以定义不同的Interpolator,就好像多个动画的拼接,第一个动画的结束点是第二个动画的开始点。KeyFrame是抽象类,要通过ofInt(),ofFloat(),ofObject()获得适当的KeyFrame,然后通过PropertyValuesHolder.ofKeyframe获得PropertyValuesHolder对象,如以下例子:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. Keyframe kf0 = Keyframe.ofInt(0400);  
  2. Keyframe kf1 = Keyframe.ofInt(0.25f, 200);  
  3. Keyframe kf2 = Keyframe.ofInt(0.5f, 400);  
  4. Keyframe kf4 = Keyframe.ofInt(0.75f, 100);  
  5. Keyframe kf3 = Keyframe.ofInt(1f, 500);  
  6. PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("width", kf0, kf1, kf2, kf4, kf3);  
  7. ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(btn2, pvhRotation);  
  8. rotationAnim.setDuration(2000);  

        上述代码的意思为:设置btn对象的width属性值使其:
开始时 Width=400
动画开始1/4时 Width=200
动画开始1/2时 Width=400
动画开始3/4时 Width=100
动画结束时 Width=500
        第一个参数为时间百分比,第二个参数是在第一个参数的时间时的属性值。
定义了一些Keyframe后,通过PropertyValuesHolder类的方法ofKeyframe一个PropertyValuesHolder对象,然后通过ObjectAnimator.ofPropertyValuesHolder获得一个Animator对象。
用下面的代码可以实现同样的效果(上述代码时间值是线性,变化均匀):


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. ObjectAnimator oa=ObjectAnimator.ofInt(btn2, "width"400,200,400,100,500);  
  2. oa.setDuration(2000);  
  3. oa.start();  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值