Android中动画分为:View动画、帧动画(也属于View动画)、属性动画。
View动画是对View做图形变换(平移、缩放、旋转、透明度)从而产生动画效果。
帧动画就是顺序播放一系列图片来产生动画效果。
属性动画可以动态改变对象的属性来达到动画效果。
一、View动画
View动画的平移、缩放、旋转、透明度 分别对应 Animation的的4个子类:TranslateAnimation、ScaleAnimation、RotateAnimation、AlphaAnimation。View可以用xml定义、也可以用代码创建。推荐使用xml,可读性好。
1.1 xml方式
如下所示,R.anim.animation_test 是xml定义的动画。 其中标签 translate、scale、alpha、rotate,就是对应四种动画。set标签是动画集合,对应AnimationSet类,有多个动画构成。
其中android:duration是指动画时间,fillAfter为true是动画结束后保持,false会回到初始状态。interpolator是指动画的执行速度,默认是先加速后减速。其他标签及属性较简单可自行研究验证。
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android"
3 android:duration="5000"
4 android:fillAfter="true"
5 android:interpolator="@android:anim/accelerate_decelerate_interpolator">
6 <!--set里面的duration如果有值,会覆盖子标签的duration-->
7
8 <translate
9 android:duration="1000"
10 android:fromXDelta="0"
11 android:toXDelta="400" />
12 <scale
13 android:duration="2000"
14 android:fromXScale="0.5"
15 android:fromYScale="0.5"
16 android:toXScale="1"
17 android:toYScale="1" />
18 <alpha
19 android:duration="3000"
20 android:fromAlpha="0.2"
21 android:toAlpha="1" />
22
23 <rotate
24 android:fromDegrees="0"
25 android:toDegrees="90" />
26</set>
定义好动画后,使用也很简单,调用view的startAnimation方法即可。
1 //view动画使用,方式一:xml,建议使用。
2 Animation animation = AnimationUtils.loadAnimation(this, R.anim.animation_test);
3 textView1.startAnimation(animation);
1.2 代码动态创建
代码创建举例如下,也很简单。
1 //view动画使用,方式二:new 动画对象
2 AnimationSet animationSet = new AnimationSet(false);
3 animationSet.setDuration(3000);
4 animationSet.addAnimation(new TranslateAnimation(0, 100, 0, 0));
5 animationSet.addAnimation(new ScaleAnimation(0.1f, 1f, 0.1f, 1f));
6 animationSet.setFillAfter(true);
7 textView2.startAnimation(animationSet);
8
9 //view动画使用,方式二:new 动画对象,使用setAnimation
10 AnimationSet animationSet2 = new AnimationSet(false);
11 animationSet2.setDuration(3000);
12 animationSet2.addAnimation(new TranslateAnimation(0, 100, 0, 0));
13 animationSet2.addAnimation(new ScaleAnimation(0.1f, 1f, 0.1f, 1f));
14 animationSet2.setFillAfter(true);
15 animationSet2.setAnimationListener(new Animation.AnimationListener() {
16 @Override
17 public void onAnimationStart(Animation animation) {
18
19 }
20 @Override
21 public void onAnimationEnd(Animation animation) {
22 MyToast.showMsg(AnimationTestActivity.this, "View动画:代码 set:View动画结束~");
23 }
24 @Override
25 public void onAnimationRepeat(Animation animation) {
26
27 }
28 });
29 textView3.setAnimation(animationSet2);
注意点:
startAnimation方法是立刻播放动画;setAnimation是设置要播放的下一个动画。
setAnimationListener可以监听动画的开始、结束、重复。
1.3 自定义View动画
自定义View动画,需要继承Animation,重写initialize和applyTransformation方法。在initialize中做初始化工作,在applyTransformation中做相应的矩阵变换(需要用到Camera),需要用到数学知识。这个给出一个例子Rotate3dAnimation,沿Y轴旋转并沿Z轴平移,到达3d效果。
1/**
2 * 沿Y轴旋转并沿Z轴平移,到达3d效果
3 * An animation that rotates the view on the Y axis between two specified angles.
4 * This animation also adds a translation on the Z axis (depth) to improve the effect.
5 */
6public class Rotate3dAnimation extends Animation {
7 private final float mFromDegrees;
8 private final float mToDegrees;
9 private final float mCenterX;
10 private final float mCenterY;
11 private final float mDepthZ;
12 private final boolean mReverse;
13 private Camera mCamera;
14
15 /**
16 * Creates a new 3D rotation on the Y axis. The rotation is defined by its
17 * start angle and its end angle. Both angles are in degrees. The rotation
18 * is performed around a center point on the 2D space, definied by a pair
19 * of X and Y coordinates, called centerX and centerY. When the animation
20 * starts, a translation on the Z axis (depth) is performed. The length
21 * of the translation can be specified, as well as whether the translation
22 * should be reversed in time.
23 *
24 * @param fromDegrees the start angle of the 3D rotation 沿y轴旋转开始角度
25 * @param toDegrees the end angle of the 3D rotation 沿y轴旋转结束角度
26 * @param centerX the X center of the 3D rotation 沿y轴旋转的轴点x(相对于自身)
27 * @param centerY the Y center of the 3D rotation 沿y轴旋转的轴点y(相对于自身)
28 * @param depthZ z轴的平移。如果>0,越大就越远离,视觉上变得越小。
29 * @param reverse true if the translation should be reversed, false otherwise
30 */
31 public Rotate3dAnimation(float fromDegrees, float toDegrees,
32 float centerX, float centerY, float depthZ, boolean reverse) {
33 mFromDegrees = fromDegrees;
34 mToDegrees = toDegrees;
35 mCenterX = centerX;
36 mCenterY = centerY;
37 mDepthZ = depthZ;
38 mReverse = reverse;
39 }
40
41 @Override
42 public void initialize(int width, int height, int parentWidth, int parentHeight) {
43 super.initialize(width, height, parentWidth, parentHeight);
44 mCamera = new Camera();
45 }
46
47 @Override
48 protected void applyTransformation(float interpolatedTime, Transformation t) {
49 final float fromDegrees = mFromDegrees;
50 float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
51
52 final float centerX = mCenterX;
53 final float centerY = mCenterY;
54 final Camera camera = mCamera;
55
56 final Matrix matrix = t.getMatrix();
57
58 camera.save();
59 if (mReverse) {
60 camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
61 } else {
62 camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
63 }
64 camera.rotateY(degrees);
65 camera.getMatrix(matrix);
66 camera.restore();
67
68 matrix.preTranslate(-centerX, -centerY);
69 matrix.postTranslate(centerX, centerY);
70 }
71}
1.4 帧动画
帧动画对应AnimationDrawable类,用来顺序播放多张图片。使用很简单,先xml定义一个AnimationDrawable,然后作为背景或资源设置给view并开始动画即可。 举例如下:
1R.drawable.frame_animation
2
3<?xml version="1.0" encoding="utf-8"?>
4<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
5 android:oneshot="false">
6 <item
7 android:drawable="@drawable/home_icon_guide00"
8 android:duration="50"/>
9 <item
10 android:drawable="@drawable/home_icon_guide01"
11 android:duration="50"/>
12 <item
13 android:drawable="@drawable/home_icon_guide02"
14 android:duration="50"/>
15 <item
16 android:drawable="@drawable/home_icon_guide03"
17 android:duration="50"/>
18 ......
19</animation-list>
1 tvFrameAnimation.setBackgroundResource(R.drawable.frame_animation);
2 AnimationDrawable frameAnimationBackground = (AnimationDrawable) tvFrameAnimation.getBackground();
3 frameAnimationBackground.start();
1.5 View动画的特殊使用场景
1.5.1 给ViewGroup指定child的出场动画
1.先用xml定义标签LayoutAnimation:
android:animation设置child的出场动画 android:animationOrder设置child的出场顺序,normal就是顺序 delay是指:每个child延迟(在android:animation中指定的动画时间)0.8倍后播放动画。如果android:animation中的动画时间是100ms,那么每个child都会延迟800ms后播放动画。如果不设置delay,那么所有child同时执行动画。
1<?xml version="1.0" encoding="utf-8"?>
2<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
3 android:animation="@anim/enter_from_left_for_child_of_group"
4 android:animationOrder="normal"
5 android:delay="0.8">
6</layoutAnimation>
1R.anim.enter_from_left_for_child_of_group
2
3<?xml version="1.0" encoding="utf-8"?>
4<set xmlns:android="http://schemas.android.com/apk/res/android">
5 <translate
6 android:duration="1000"
7 android:fromXDelta="-100%p"
8 android:toXDelta="0"/>
9
10</set>
2.把LayoutAnimation设置给ViewGroup
1 <LinearLayout
2 android:id="@+id/ll_layout_animation"
3 android:layout_width="match_parent"
4 android:layout_height="wrap_content"
5 android:orientation="horizontal"
6 android:layoutAnimation="@anim/layout_animation">
7 <TextView
8 android:layout_width="50dp"
9 android:layout_height="wrap_content"
10 android:textColor="#ff0000"
11 android:text="呵呵呵"/>
12 <TextView
13 android:layout_width="60dp"
14 android:layout_height="wrap_content"
15 android:textColor="#ff0000"
16 android:text="qq"
17 android:background="@color/colorPrimary"/>
18 <TextView
19 android:layout_width="30dp"
20 android:layout_height="wrap_content"
21 android:textColor="#ff0000"
22 android:text="啊啊"/>
23 </LinearLayout>
除了xml,当然也可以使用LayoutAnimationController 指定:
1 //代码设置LayoutAnimation,实现ViewGroup的child的出场动画
2 Animation enterAnim = AnimationUtils.loadAnimation(this, R.anim.enter_from_left_for_child_of_group);
3 LayoutAnimationController controller = new LayoutAnimationController(enterAnim);
4 controller.setDelay(0.8f);
5 controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
6 llLayoutAnimation.setLayoutAnimation(controller);
1.5.2 Activity的切换效果 Activity默认有切换动画效果,我们也可以自定义:overridePendingTransition(int enterAnim, int exitAnim) 可以指定activity开大或暂停时的动画效果。
enterAnim,指要打开的activity进入的动画 exitAnim,要暂停的activity退出的动画 注意 必须在startActivity或finish之后使用才能生效。如下所示:
1 public static void launch(Activity activity) {
2 Intent intent = new Intent(activity, AnimationTestActivity.class);
3 activity.startActivity(intent);
4 //打开的activity,从右侧进入,暂停的activity退出到左侧。
5 activity.overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left);
6 }
7......
8
9 @Override
10 public void finish() {
11 super.finish();
12 //打开的activity,就是上一个activity从左侧进入,要finish的activity退出到右侧
13 overridePendingTransition(R.anim.enter_from_left, R.anim.exit_to_right);
14 }
R.anim.enter_from_right
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android">
3 <translate
4 android:duration="500"
5 android:fromXDelta="100%p"
6 android:toXDelta="0"/>
7</set>
R.anim.exit_to_left
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android">
3 <translate
4 android:duration="500"
5 android:fromXDelta="0"
6 android:toXDelta="-100%p"/>
7</set>
R.anim.enter_from_left
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android">
3 <translate
4 android:duration="500"
5 android:fromXDelta="-100%p"
6 android:toXDelta="0"/>
7
8</set>
R.anim.exit_to_right
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android">
3 <translate
4 android:duration="500"
5 android:fromXDelta="-100%p"
6 android:toXDelta="0"/>
7
8</set>
二、属性动画
属性动画几乎无所不能,只要对象有这个属性,就可以对这个属性做动画。甚至还可以没有对象。可用通过ObjectAnimator、ValueAnimator、AnimatorSet实现丰富的动画。
2.1 使用方法
属性动画可对任意对象做动画,不仅仅是View。默认动画时间是300ms,10ms/帧。具体理解就是:可在给定的时间间隔内 实现 对象的某属性值 从 value1 到 value2的改变。
使用很简单,可以直接代码实现(推荐),也可xml实现,举例如下:
1 //属性动画使用,方式一:代码,建议使用。 横移
2 ObjectAnimator translationX = ObjectAnimator
3 .ofFloat(textView6, "translationX", 0, 200)
4 .setDuration(1000);
5 translationX.setInterpolator(new LinearInterpolator());
6 setAnimatorListener(translationX);
7
8 //属性动画使用,方式二:xml。 竖移
9 Animator animatorUpAndDown = AnimatorInflater.loadAnimator(this, R.animator.animator_test);
10 animatorUpAndDown.setTarget(textView6);
11
12 //文字颜色变化
13 ObjectAnimator textColor = ObjectAnimator
14 .ofInt(textView6, "textColor", 0xffff0000, 0xff00ffff)
15 .setDuration(1000);
16 textColor.setRepeatCount(ValueAnimator.INFINITE);
17 textColor.setRepeatMode(ValueAnimator.REVERSE);
18 //注意,这里如果不设置 那么颜色就是跳跃的,设置ArgbEvaluator 就是连续过度的颜色变化
19 textColor.setEvaluator(new ArgbEvaluator());
20
21 //animatorSet
22 mAnimatorSet = new AnimatorSet();
23 mAnimatorSet
24 .play(animatorUpAndDown)
25 .with(textColor)
26 .after(translationX);
27
28 mAnimatorSet.start();
29
30
31 /**
32 * 设置属性动画的监听
33 * @param translationX
34 */
35 private void setAnimatorListener(ObjectAnimator translationX) {
36 translationX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
37 @Override
38 public void onAnimationUpdate(ValueAnimator animation) {
39 //每播放一帧,都会调用
40 }
41 });
42 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
43 translationX.addPauseListener(new AnimatorListenerAdapter() {
44 @Override
45 public void onAnimationResume(Animator animation) {
46 super.onAnimationResume(animation);
47 }
48 });
49 }
50
51 translationX.addListener(new AnimatorListenerAdapter() {
52 @Override
53 public void onAnimationEnd(Animator animation) {
54 super.onAnimationEnd(animation);
55 }
56 });
57 }
R.animator.animator_test,是放在res/animator中。
1<?xml version="1.0" encoding="utf-8"?>
2<!--属性动画test,一般建议采用代码实现,不用xml-->
3<set xmlns:android="http://schemas.android.com/apk/res/android"
4 android:ordering="sequentially">
5
6
7 <!--repeatCount:默认是0,-1是无限循环-->
8 <!--repeatMode:重复模式:restart-从头来一遍、reverse-反向来一遍-->
9 <!--valueType:指定propertyName的类型可选intType、floatType-->
10
11 <!--android:pathData=""
12 android:propertyXName=""
13 android:propertyYName=""-->
14 <objectAnimator
15 android:propertyName="translationY"
16 android:duration="1000"
17 android:valueFrom="0"
18 android:valueTo="120"
19 android:startOffset="0"
20 android:repeatCount="0"
21 android:repeatMode="reverse"
22 android:valueType="floatType"
23 android:interpolator="@android:interpolator/accelerate_decelerate" />
24
25 <!--animator对用vueAnimator,比objectAnimator少了propertyName-->
26 <!--<animator-->
27 <!--android:duration="2000"-->
28 <!--android:valueFrom=""-->
29 <!--android:valueTo=""-->
30 <!--android:startOffset=""-->
31 <!--android:repeatCount=""-->
32 <!--android:repeatMode=""-->
33 <!--android:valueType=""-->
34 <!--android:interpolator=""-->
35 <!--android:pathData=""-->
36 <!--android:propertyXName=""-->
37 <!--android:propertyYName=""/>-->
38
39</set>
translationX是实现横移,animatorUpAndDown是实现竖移、textColor是实现文字颜色变化。其中animatorUpAndDown是使用xml定义,标签含义也很好理解。最后使用AnimatorSet的play、with、after 实现 先横移,然后 竖移和颜色变化 同时的动画集合效果。
注意点:
关于View动画和属性动画的平移,属性动画改变属性值setTranslationX 的视图效果像view动画的平移一样,都是view实际的layout位置没变,只改变了视图位置;不同点是属性动画 给触摸点生效区域增加了位移(而view动画仅改变了视图位置)。
插值器:Interpolator,根据 时间流逝的百分比,计算当前属性值改变的百分比。 例如duration是1000,start后过了200,那么时间百分比是0.2,那么如果差值器是LinearInterpolator线性差值器,那么属性值改变的百分比也是0.2
估值器:Evaluator,就是根据 差值器获取的 属性值百分比,计算改变后的属性值。ofInt、onFloat内部会自动设置IntEvaluator、FloatEvaluator。如果使用ofInt且是颜色相关的属性,就要设置ArgbEvaluator。上面例子中 文字颜色变化动画 设置了ArgbEvaluator:textColor.setEvaluator(new ArgbEvaluator())。
动画监听:主要是两个监听接口,AnimatorUpdateListener、AnimatorListenerAdapter。AnimatorUpdateListener的回调方法在每帧更新时都会调用一次;AnimatorListenerAdapter可以监听开始、结束、暂停、继续、重复、取消,重写你要关注的方法即可。
2.2对任意属性做动画
一个问题,针对下面的Button,如何实现 的宽度逐渐拉长的动画,即文字不变,仅拉长背景宽度?
1 <Button
2 android:id="@+id/button_animator_test"
3 android:layout_width="180dp"
4 android:layout_height="wrap_content"
5 android:text="任意属性动画-宽度拉长"/>
首先,View动画的ScaleAnimation是无法实现的,因为view的scale是把view的视图放大,这样文字也会拉长变形。那么属性动画呢?试试~
1 ObjectAnimator width1 = ObjectAnimator.ofInt(button, "width", 1000);
2 width1.setDuration(2000);
3 width1.start();
对object 的任意属性做动画 要求两个条件:
object有 对应属性 的set方法,动画中没设置初始值 还要有get方法,系统要去取初始值(不满足则会crash)。 set方法要对object有所改变,如UI的变化。不满足则会没有动画效果 上面Button没有动画效果,就是没有满足第二条。看下Button的setWidth方法:
1 public void setWidth(int pixels) {
2 mMaxWidth = mMinWidth = pixels;
3 mMaxWidthMode = mMinWidthMode = PIXELS;
4 requestLayout();
5 invalidate();
6 }
实际就是TextView的setWidth方法,看到设置进去的值仅影响了宽度最大值和最小值。按照官方注释和实测,发现只有当Button/TextView在xml中设置android:layout_width为"wrap_content"时,才会setWidth改变宽度;而当Button/TextView在xml中设置android:layout_width为固定dp值时,setWidth无效。而我们上面给出的Button xml中确实是固定值180dp,所以是属性"width"的setWidth是无效的,即不满足第二条要求,就没有动画效果了。(当修改Button xml中设置android:layout_width为"wrap_content"时,上面执行的属性动画是生效的。)
那么,当不满足条件时,如何解决此问题呢?有如下处理方法:
给object添加set、get方法,如果有权限。(一般不行,如TextView是SDK里面的不能直接改)
给Object包装一层,在包装类中提供set、get方法。
使用ValueAnimator,监听Value变化过程,自己实现属性的改变。
1 private void testAnimatorAboutButtonWidth() {
2 //Button width 属性动画:如果xml中宽度是wrap_content,那么动画有效。
3 // 如果设置button确切的dp值,那么无效,因为对应属性"width"的setWidth()方法就是 在wrap_content是才有效。
4 ObjectAnimator width1 = ObjectAnimator.ofInt(button, "width", 1000);
5 width1.setDuration(2000);
6// width1.start();
7
8 //那么,想要在button原本有确切dp值时,要能对width动画,怎么做呢?
9 //方法一,包一层,然后用layoutParams
10 ViewWrapper wrapper = new ViewWrapper(button);
11 ObjectAnimator width2 = ObjectAnimator.ofInt(wrapper, "width", 1000);
12 width2.setDuration(2000);
13// width2.start();
14
15 //方法二,使用ValueAnimator,每一帧自己显示宽度的变化
16 ValueAnimator valueAnimator = ValueAnimator.ofInt(button.getLayoutParams().width, 1000);
17 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
18 @Override
19 public void onAnimationUpdate(ValueAnimator animation) {
20 int animatedValue = (Integer) animation.getAnimatedValue();
21 Log.i("hfy", "onAnimationUpdate: animatedValue=" + animatedValue);
22
23// IntEvaluator intEvaluator = new IntEvaluator();
24//// 获取属性值改变比例、计算属性值
25// float animatedFraction = animation.getAnimatedFraction();
26// Integer evaluate = intEvaluator.evaluate(animatedFraction, 300, 600);
27// Log.i("hfy", "onAnimationUpdate: evaluate="+evaluate);
28
29
30 if (button != null) {
31 button.getLayoutParams().width = animatedValue;
32 button.requestLayout();
33 }
34 }
35 });
36
37 valueAnimator.setDuration(4000).start();
38
39 }
40
41 /**
42 * 包一层,提供对应属性的set、get方法
43 */
44 private class ViewWrapper {
45
46 private final View mView;
47
48 public ViewWrapper(View view) {
49 mView = view;
50 }
51
52 public int getWidth() {
53 return mView.getLayoutParams().width;
54 }
55
56 public void setWidth(int width) {
57 ViewGroup.LayoutParams layoutParams = mView.getLayoutParams();
58 layoutParams.width = width;
59 mView.setLayoutParams(layoutParams);
60 mView.requestLayout();
61 }
62 }
2.3 属性动画的原理
属性动画,要求对象有这个属性的set方法,执行时会根据传入的 属性初始值、最终值,在每帧更新时调用set方法设置当前时刻的 属性值。随着时间推移,set的属性值会接近最终值,从而达到动画效果。如果没传入初始值,那么对象还要有get方法,用于获取初始值。
在获取初始值、set属性值时,都是使用 反射 的方式,进行 get、set方法的调用。 见PropertyValuesHolder的setupValue、setAnimatedValue方法:
1 private void setupValue(Object target, Keyframe kf) {
2 if (mProperty != null) {
3 Object value = convertBack(mProperty.get(target));
4 kf.setValue(value);
5 } else {
6 try {
7 if (mGetter == null) {
8 Class targetClass = target.getClass();
9 setupGetter(targetClass);
10 if (mGetter == null) {
11 // Already logged the error - just return to avoid NPE
12 return;
13 }
14 }
15 Object value = convertBack(mGetter.invoke(target));
16 kf.setValue(value);
17 } catch (InvocationTargetException e) {
18 Log.e("PropertyValuesHolder", e.toString());
19 } catch (IllegalAccessException e) {
20 Log.e("PropertyValuesHolder", e.toString());
21 }
22 }
23 }
1 void setAnimatedValue(Object target) {
2 if (mProperty != null) {
3 mProperty.set(target, getAnimatedValue());
4 }
5 if (mSetter != null) {
6 try {
7 mTmpValueArray[0] = getAnimatedValue();
8 mSetter.invoke(target, mTmpValueArray);
9 } catch (InvocationTargetException e) {
10 Log.e("PropertyValuesHolder", e.toString());
11 } catch (IllegalAccessException e) {
12 Log.e("PropertyValuesHolder", e.toString());
13 }
14 }
15 }
三、使用动画的注意事项
使用帧动画,避免OOM。因为图片多。
属性动画 如果有循环动画,在页面退出时要及时停止,避免内存泄漏。
使用View动画后,调用setVisibility(View.GONE)失效时,使用view.clearAnimation()可解决。