关于ObjectAnimator 笔记

63 阅读1分钟

基本使用

    ObjectAnimator animator = ObjectAnimator.ofFloat(view,"alpha",1,0,1);
    animator.start();

关键点在于第二个参数:String propertyName 如果需要使用这个参数对应的效果,需要操作的view中有对应的set属性方法(set 函数的命名必须采用骆驼拼写法)。 例如:alpha 对应 setAlpha()方法

image.png 引用自《Android自定义控件开发入门与实战》

所以ValueAnimator 一般在回调中操作,而ObjectAnimator方便在自定义view中调用相应的方法。

关于ofObject()的使用

ofObject()可以帮助我们处理的值不限于int或者float,我们可以传自定义的值进行处理,如对象。

使用实例:

ObjectAnimator animator = ObjectAnimator.ofObject(view,"jump",new JumpEvaluator(),new Point(0,0),new Point(3030));
animator.setDuration(299);
animator.start();
public class JumpEvaluator implements TypeEvalutor<Point>{
    private Point point = new Point();
   
    @Override
    public Point evaluate(float fraction, Point startValue, Point endValue) { 
        //自己的逻辑
        //point.x = (int)(startValue.x + fraction *(endValue.x - startValue.x));
        //if (fraction*2<=1){ 
        //    point.y = (int)(startValue.y + fraction*2*(endValue.y - startValue.y));
        // }else { 
        //    point.y = endValue.y; 
        //} 
    return point;
}

注意

对于ofFloat(),ofInt()最后一个可变参数,如果只传一个值,因为对应的get方法,而float,int 对应默认值为0,所以系统会报警告但不至于崩溃,而ofObject()对应的属性,没有默认的get方法,所以单个参数会崩溃

其他

void setRepeatCount(int value) //设置循环次数,设置为 INFINITE 表示无限循环