Android中重复执行动画bug

来源:互联网 发布:java项目视频20套 编辑:程序博客网 时间:2024/06/14 02:42

在android中我们要经常用到看似一个没有时间限制的重复动画,如最常见的下拉刷新和上拉加载更多的loading加载动画:

    今天尝试了三种动画(以旋转为例):
package com.example.anim.anim;import android.animation.Animator;import android.animation.ObjectAnimator;import android.animation.ValueAnimator;import android.view.View;import android.view.animation.Animation;import android.view.animation.LinearInterpolator;import android.view.animation.RotateAnimation;/** * Created by houruixiang on 2017/8/15. */public class SimpleAnim {    private static ValueAnimator valueAnimator;    public static void startAnim(View view){        RotateAnimation rotateAnimation = new RotateAnimation(0, 360f,                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);        rotateAnimation.setDuration(2000);        rotateAnimation.setFillAfter(true);        rotateAnimation.setRepeatCount(-1);        view.startAnimation(rotateAnimation);    }    public static void startOjAnim(View view){        ObjectAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", 0, 360f);        rotation.setDuration(2000);        rotation.setRepeatCount(-1);        rotation.start();    }    public static void startValueAnim(final View view){        valueAnimator = ValueAnimator.ofFloat(0f, 360.0f);        //valueAnimator.setTarget(view);        //valueAnimator.setRepeatMode(ValueAnimator.RESTART);        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);        valueAnimator.setDuration(1000);        valueAnimator.start();        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {            @Override            public void onAnimationUpdate(ValueAnimator valueAnimator) {                float animatedValue = (float) valueAnimator.getAnimatedValue();                view.setRotation(animatedValue);            }        });    }}

都存在这个问题,之前遇到这个问题,会误认为是补间动画和属性动画的差别,今天试了之后,都一样;抑或是restart的延迟造成的
其实都不是,只是动画的执行不是匀速的,所以当设置一个匀速插值器之后就完美解决问题;看下面代码(以valueAnimation为例):

public static void startValueAnim(final View view){        valueAnimator = ValueAnimator.ofFloat(0f, 360.0f);        //valueAnimator.setTarget(view);        //valueAnimator.setRepeatMode(ValueAnimator.RESTART);        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);        valueAnimator.setDuration(1000);        valueAnimator.setInterpolator(new LinearInterpolator());        valueAnimator.start();        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {            @Override            public void onAnimationUpdate(ValueAnimator valueAnimator) {                float animatedValue = (float) valueAnimator.getAnimatedValue();                view.setRotation(animatedValue);            }        });    }

关键代码:valueAnimator.setInterpolator(new LinearInterpolator());
ok,比较简单,感谢阅读,共同进步

原创粉丝点击