前言
最近和同学聊天、看别人的博客,发现自己实现的方式太繁琐了,有很大的优化空间。在这里,利用自定义 Interpolator、属性动画的两个类 ValueAnimator 和 ObjectAnimator对我之前的实现进行优化。
优化
1.利用自定义interpolator,来实现一个Animation 的逆向 Animation。即可以少自定义一个 Animation 类。
final static class CounterAnticipateInterpolator implements Interpolator{
private float mTension;
CounterAnticipateInterpolator() {
mTension = 2.0f;
}
CounterAnticipateInterpolator(int mTension) {
this.mTension = mTension;
}
@Override
public float getInterpolation(float t) {
return 1 - (t * t * ((mTension + 1) * t - mTension));
}
}
2.当然也可以通过 valueAnimtor 的 addUpdateListener 实现节拍器,不必去自定义 Animation 类。
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
if (checked){
valueAnimator.setInterpolator(new OvershootInterpolator());
} else {
valueAnimator.setInterpolator(new CounterAnticipateInterpolator());
}
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
update((Float) animation.getAnimatedValue());
}
});
valueAnimator.setDuration(300);
valueAnimator.start();
3.当然我们还可以更进一步,自定义 property,利用 ObjectAnimator,自动的去改变绘制参数,而不必手动的去 update。
private float interpolatedTime;
public float getInterpolatedTime() {
return interpolatedTime;
}
public void setInterpolatedTime(float interpolatedTime) {
this.interpolatedTime = interpolatedTime;
}
private static final Property<MaterialRadioButton, Float> MATERIAL_RADIO_BUTTON_PROGRESS_PROPERTY = new Property<MaterialRadioButton, Float>(Float.class, "MATERIAL_RADIO_BUTTON_PROGRESS_PROPERTY") {
@Override
public void set(MaterialRadioButton object, Float value) {
object.setInterpolatedTime(value);
}
@Override
public Float get(MaterialRadioButton object) {
return object.getInterpolatedTime();
}
};
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(this, MATERIAL_RADIO_BUTTON_PROGRESS_PROPERTY, 0 , 1);
if (checked){
objectAnimator.setInterpolator(new OvershootInterpolator());
} else {
objectAnimator.setInterpolator(new CounterAnticipateInterpolator());
}
objectAnimator.setDuration(300);
objectAnimator.start();
源码
1.最终版源码
package com.sinaapp.myron.myronmaterialdesign.widget;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Property;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
public class