动画 -- 属性动画 -- 对任意属性做动画

一、概念

属性动画,是根据外界传递的某个属性的初始值和最终值,以动画的效果多次去调用set方法,每次传递给set方法的值都不一样,确切来说是随着时间的推移,所传递的值越来越接近最终值。

二、属性动画生效条件

对object的属性abc做动画,如果想让动画生效,要同时满足两个条件,缺一不可:

  1. object必须要提供setAbc方法,如果动画的时候没有传递初始值,那么还需要提供getAbc方法,因为系统要去取abc属性的初始值。
  2. object的setAbc方法对属性abc所做的改变必须能够通过某种方式反映出来,比如会带来UI的改变之类的。

例子:对TextView的width属性做动画

//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/main_tv"
        android:layout_width="100px" //注意:这里要设置固定大小,而不能设置wrap_content
        android:layout_height="100px"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:text="Hello Android!"
        android:background="@color/colorPrimary"/>
</RelativeLayout>

//代码,MainActivity
private void startTextViewWidthAnimator() {
    ObjectAnimator.ofInt(mMain_tv, "width", 100,500).setDuration(5000).start();
}

上述代码运行后发现没效果,需要分析width属性的setWidth方法和getWidth方法,
源码如下:

//TextView.java
public void setWidth(int pixels) {
    mMaxWidth = mMinWidth = pixels; //注意:这里是设置最大宽度跟最小宽度,而不是设置当前宽度
    mMaxWidthMode = mMinWidthMode = PIXELS;

    requestLayout();
    invalidate();
}

//View.java
public final int getWidth() {
    return mRight - mLeft; //获取当前宽度
}

由于setWidth方法无法改变TextView当前宽度,所以对width做属性动画没有效果。

如果把布局文件中TextView的属性android:layout_width从"100px"改为"wrap_content",则动画有效果。源码如下:

//TextView.java
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    ...
    width += getCompoundPaddingLeft() + getCompoundPaddingRight();

    if (mMaxWidthMode == EMS) {
        width = Math.min(width, mMaxWidth * getLineHeight());
    } else {
        width = Math.min(width, mMaxWidth);
    }

    if (mMinWidthMode == EMS) {
        width = Math.max(width, mMinWidth * getLineHeight());
    } else {
        width = Math.max(width, mMinWidth);
    }

    // Check against our minimum width
    width = Math.max(width, getSuggestedMinimumWidth());

    if (widthMode == MeasureSpec.AT_MOST) {
        width = Math.min(widthSize, width);
    }
    ...
}

//View.java
protected int getSuggestedMinimumWidth() {
    return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

当SpecMode为AT_MOST时,TextView当前宽度会受mMinWidth跟mMaxWidth影响,因此setWidth方法可以改变TextView当前宽度,此时动画有效果。

三、属性动画生效方法

方法1:如果有权限的话,给对象加上get和set方法
很多时候我们没权限去这么做,比如TextView的代码是Android SDK内部实现的,没办法添加代码。

方法2:用一个类来包装原始对象,间接为其提供set和get方法(推荐)

//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/main_tv"
        android:layout_width="100px" //这里设置固定大小或wrap_content都可以
        android:layout_height="100px"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:text="Hello Android!"
        android:background="@color/colorPrimary"/>
</RelativeLayout>

//代码,MainActivity
//内部类
private static class ViewWrapper {
    private View mTarget;

    public ViewWrapper(View target) {
        mTarget = target;
    }

    public int getWidth() {
        return mTarget.getLayoutParams().width;
    }

    public void setWidth(int width) {
        mTarget.getLayoutParams().width = width;
        mTarget.requestLayout();
    }
}

private void startTextViewWidthAnimator() {
    ViewWrapper viewWrapper = new ViewWrapper(mMain_tv);
    ObjectAnimator.ofInt(viewWrapper, "width", 100,500).setDuration(5000).start();
}

方法3:采用ValueAnimator,监听动画过程,自己实现属性改变

//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/main_tv"
        android:layout_width="100px"
        android:layout_height="100px"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:text="Hello Android!"
        android:background="@color/colorPrimary"/>
</RelativeLayout>

//代码,MainActivity
private void startTextViewWidthAnimator(final View target, final int start, final int end, int duration) {
    final ValueAnimator valueAnimator = ValueAnimator.ofInt(start, end);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        private  IntEvaluator mEvaluator = new IntEvaluator();

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
           int currentValue = (Integer)animation.getAnimatedValue();
            Log.d("AnimatorUpdateListener", "zwm, currentValue: " + currentValue);

            //获取当前进度占整个动画过程的比例
            float fraction = animation.getAnimatedFraction();
            //计算当前属性值
            int currentValue2 = mEvaluator.evaluate(fraction, start, end);
            Log.d("AnimatorUpdateListener", "zwm, currentValue2: " + currentValue2);

            target.getLayoutParams().width = currentValue2;
            target.requestLayout();
        }
    });
    valueAnimator.setDuration(duration).start();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    startTextViewWidthAnimator(mMain_tv, 100, 500, 5000);
}

上述代码运行后发现,onAnimationUpdate方法中的currentValue跟currentValue2两个值是一样的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。