@linux1s1s
2017-01-22T08:26:33.000000Z
字数 12230
阅读 4927
AndroidAnimation 2016-06
为什么会有属性动画?因为前面补间动画和帧动画不能胜任复杂动画,所以属性动画应运而生。
了解属性动画前需要对下面这些属性门清
Duration动画的持续时间,默认300ms。
Time interpolation:时间差值,乍一看不知道是什么,但是我说LinearInterpolator、AccelerateDecelerateInterpolator,大家一定知道是干嘛的了,定义动画的变化率。
Repeat count and behavior:重复次数、以及重复模式;可以定义重复多少次;重复时从头开始,还是反向。
Animator sets: 动画集合,你可以定义一组动画,一起执行或者顺序执行。
Frame refresh delay:帧刷新延迟,对于你的动画,多久刷新一次帧;默认为10ms,但最终依赖系统的当前状态;基本不用管。
接下来分别介绍属性动画的相关类,我们从简单的开始
这个类比较简单,我们直接看如何使用即可
@TargetApi(VERSION_CODES.HONEYCOMB)private void rotate(View view){ObjectAnimator.ofFloat(view, "rotationX", 0.0f, 360.0f).setDuration(100).start();}
如果我们设置一个背景图的点击事件,然后调用这个
rotate()方法,那么这个背景图就会沿着X轴旋转360度,哪里定义非得沿着X轴旋转了呢?我们先来看看ofFloat()这个静态方法
public static ObjectAnimator ofFloat(Object target, String propertyName, float... values) {ObjectAnimator anim = new ObjectAnimator(target, propertyName);anim.setFloatValues(values);return anim;}private ObjectAnimator(Object target, String propertyName) {setTarget(target);setPropertyName(propertyName);}public void setPropertyName(@NonNull String propertyName) {// mValues could be null if this is being constructed piecemeal. Just record the// propertyName to be used later when setValues() is called if so.if (mValues != null) {PropertyValuesHolder valuesHolder = mValues[0];String oldName = valuesHolder.getPropertyName();valuesHolder.setPropertyName(propertyName);mValuesMap.remove(oldName);mValuesMap.put(propertyName, valuesHolder);}mPropertyName = propertyName;// New property/values/target should cause re-initialization prior to startingmInitialized = false;}
然后就进一步跟踪到PropertyValuesHolder这个类中的setPropertyName方法
/*** Sets the name of the property that will be animated. This name is used to derive* a setter function that will be called to set animated values.* For example, a property name of <code>foo</code> will result* in a call to the function <code>setFoo()</code> on the target object. If either* <code>valueFrom</code> or <code>valueTo</code> is null, then a getter function will* also be derived and called.** <p>Note that the setter function derived from this property name* must take the same parameter type as the* <code>valueFrom</code> and <code>valueTo</code> properties, otherwise the call to* the setter function will fail.</p>** @param propertyName The name of the property being animated.*/public void setPropertyName(String propertyName) {mPropertyName = propertyName;}
从上面一大段的英文注释可以看到,这里方法保存了propertyName并在合适的时机通过反射调用setxxx方法,如下
String methodName = getMethodName("set", mPropertyName);
这个给出可以操作的属性:scaleX/scaleY;rotationX/ rotationY;transitionX/ transitionY
接下来解释一下这个静态方法的参数定义
提供了ofInt、ofFloat、ofObject,这几个方法都是设置动画作用的元素、作用的属性、动画开始、结束、以及中间的任意个属性值。
当对于属性值,只设置一个的时候,会认为当然对象该属性的值为开始(getPropName反射获取),然后设置的值为终点。如果设置两个,则一个为开始、一个为结束~~~
动画更新的过程中,会不断调用setPropName更新元素的属性,所有使用ObjectAnimator更新某个属性,必须得有getter(设置一个属性值的时候)和setter方法~
上面这个例子很单一,因为仅仅涉及一个参数的变化,当我们有多个参数涉及变化,怎么办?
@TargetApi(VERSION_CODES.HONEYCOMB)private void rotate(final View view){ObjectAnimator animator = ObjectAnimator.ofFloat(view, "custom", 1.0f, 0.0f).setDuration(100);animator.start();animator.addUpdateListener(new AnimatorUpdateListener(){@Overridepublic void onAnimationUpdate(ValueAnimator animation){float val = (float) animation.getAnimatedValue();view.setAlpha(val);view.setScaleX(val);view.setScaleY(val);}});}
注意这里propertyName参数传进来的值并没有出现上面给出的几个属性值scaleX/scaleY;rotationX/ rotationY;transitionX/ transitionY,而是一个随便定义的值custom,监听一个不存在的属性的原因就是,我们只需要动画的变化值,通过这个值,我们自己来实现要修改的效果,实际上,更直接的方法,就是使用ValueAnimator来实现,其实ObjectAnimator就是ValueAnimator的子类,这个在下面会具体讲到。
上面是通过代码来实现ObjectAnimator能不能直接通过xml来定义一个标签 objectAnimator实现相同的效果呢?
当然可以,举个例子:
<?xml version="1.0" encoding="utf-8"?><objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"android:duration="1000"android:propertyName="scaleX"android:valueFrom="1.0"android:valueTo="2.0"android:valueType="floatType" ></objectAnimator>
然后在代码中加载进来即可,如下所示:
public void scaleX(View view){Animator anim = AnimatorInflater.loadAnimator(this, R.animator.scalex);anim.setTarget(view);anim.start();}
这个仅仅是当个方向的动画,如果需要多个方法的动画该肿么整?
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"android:ordering="together" ><objectAnimatorandroid:duration="1000"android:propertyName="scaleX"android:valueFrom="1"android:valueTo="0.5" ></objectAnimator><objectAnimatorandroid:duration="1000"android:propertyName="scaleY"android:valueFrom="1"android:valueTo="0.5" ></objectAnimator></set>
同样是通过XML来设置初始化值。然后通过代码实现动画
Animator anim = AnimatorInflater.loadAnimator(this, R.animator.scale);mMv.setPivotX(0);mMv.setPivotY(0);mMv.invalidate();anim.setTarget(view);anim.start();
说简单点,ValueAnimator就是一个数值产生器,他本身不作用于任何一个对象,但是可以对产生的值进行动画处理。先看个小球的例子
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/id_container"><ImageViewandroid:id="@+id/id_ball"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/bol_blue" /><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:orientation="horizontal" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="verticalRun"android:text="垂直" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="paowuxian"android:text="抛物线" /></LinearLayout></RelativeLayout>
左上角一个小球,底部两个按钮~我们先看一个自由落体的代码:
public void verticalRun( View view){ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight- mBlueBall.getHeight());animator.setTarget(mBlueBall);animator.setDuration(1000).start();// animator.setInterpolator(value)animator.addUpdateListener(new AnimatorUpdateListener(){@Overridepublic void onAnimationUpdate(ValueAnimator animation){mBlueBall.setTranslationY((Float) animation.getAnimatedValue());}});}
- 通过这个动画我们可以发现,和我们在上面提供的使用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,计算方法为 :
public Float evaluate(float fraction, Number startValue, Number endValue){float startFloat = startValue.floatValue();return startFloat + fraction * (endValue.floatValue() - startFloat);}
我们这里把监听重新拿出来说一下:
对于动画,一般都是一些辅助效果,比如我要删除个元素,我可能希望是个淡出的效果,但是最终还是要删掉,并不是你透明度没有了,还占着位置,所以我们需要知道动画如何结束。
所以我们可以添加一个动画的监听:
public void fadeOut(View view){ObjectAnimator anim = ObjectAnimator.ofFloat(mBlueBall, "alpha", 0.5f);anim.addListener(new AnimatorListener(){@Overridepublic void onAnimationStart(Animator animation){Log.e(TAG, "onAnimationStart");}@Overridepublic void onAnimationRepeat(Animator animation){// TODO Auto-generated method stubLog.e(TAG, "onAnimationRepeat");}@Overridepublic void onAnimationEnd(Animator animation){Log.e(TAG, "onAnimationEnd");ViewGroup parent = (ViewGroup) mBlueBall.getParent();if (parent != null)parent.removeView(mBlueBall);}@Overridepublic void onAnimationCancel(Animator animation){// TODO Auto-generated method stubLog.e(TAG, "onAnimationCancel");}});anim.start();}
AnimatorSet用于实现多个动画的协同作用。AnimatorSet中有一系列的顺序控制方法:playTogether、playSequentially、animSet.play().with()、defore()、after()等。用来实现多个动画的协同工作方式。
布局动画,主要使用LayoutTransition为布局的容器设置动画,当容器中的视图层次发生变化时存在过渡的动画效果。
我们来看看比较常用的方法如下:
LayoutTransition transition = new LayoutTransition();transition.setAnimator(LayoutTransition.CHANGE_APPEARING,transition.getAnimator(LayoutTransition.CHANGE_APPEARING));transition.setAnimator(LayoutTransition.APPEARING,null);transition.setAnimator(LayoutTransition.DISAPPEARING,null);transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,null);mGridLayout.setLayoutTransition(transition);
然后我们重点看一下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。
关于上面这四个参数的范例可以看看下面这个Demo
先上Layout部分
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/id_container"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="addBtn"android:text="addBtns" /><CheckBoxandroid:id="@+id/id_appear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:checked="true"android:text="APPEARING" /><CheckBoxandroid:id="@+id/id_change_appear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:checked="true"android:text="CHANGE_APPEARING" /><CheckBoxandroid:id="@+id/id_disappear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:checked="true"android:text="DISAPPEARING" /><CheckBoxandroid:id="@+id/id_change_disappear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:checked="true"android:text="CHANGE_DISAPPEARING " /></LinearLayout>
接下来看看Code
package com.example.zhy_property_animation;import android.animation.LayoutTransition;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.GridLayout;public class LayoutAnimaActivity extends Activity implementsOnCheckedChangeListener{private ViewGroup viewGroup;private GridLayout mGridLayout;private int mVal;private LayoutTransition mTransition;private CheckBox mAppear, mChangeAppear, mDisAppear, mChangeDisAppear;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.layout_animator);viewGroup = (ViewGroup) findViewById(R.id.id_container);mAppear = (CheckBox) findViewById(R.id.id_appear);mChangeAppear = (CheckBox) findViewById(R.id.id_change_appear);mDisAppear = (CheckBox) findViewById(R.id.id_disappear);mChangeDisAppear = (CheckBox) findViewById(R.id.id_change_disappear);mAppear.setOnCheckedChangeListener(this);mChangeAppear.setOnCheckedChangeListener(this);mDisAppear.setOnCheckedChangeListener(this);mChangeDisAppear.setOnCheckedChangeListener(this);mGridLayout = new GridLayout(this);mGridLayout.setColumnCount(5);viewGroup.addView(mGridLayout);mTransition = new LayoutTransition();mGridLayout.setLayoutTransition(mTransition);}public void addBtn(View view){final Button button = new Button(this);button.setText((++mVal) + "");mGridLayout.addView(button, Math.min(1, mGridLayout.getChildCount()));button.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){mGridLayout.removeView(button);}});}@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked){mTransition = new LayoutTransition();mTransition.setAnimator(LayoutTransition.APPEARING,(mAppear.isChecked() ? mTransition.getAnimator(LayoutTransition.APPEARING) : null));mTransition.setAnimator(LayoutTransition.CHANGE_APPEARING,(mChangeAppear.isChecked() ? mTransition.getAnimator(LayoutTransition.CHANGE_APPEARING): null));mTransition.setAnimator(LayoutTransition.DISAPPEARING,(mDisAppear.isChecked() ? mTransition.getAnimator(LayoutTransition.DISAPPEARING) : null));mTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,(mChangeDisAppear.isChecked() ? mTransition.getAnimator(LayoutTransition.CHANGE_DISAPPEARING): null));mGridLayout.setLayoutTransition(mTransition);}}

关于属性动画就介绍到这里,其他更深入的介绍后续会更新
参考:http://blog.csdn.net/lmj623565791/article/details/38067475