Android animation does not repeat

后端 未结 23 1465
囚心锁ツ
囚心锁ツ 2020-11-27 14:01

I\'m trying to make simple animation that would repeat several times (or infinitely).
It seems that android:repeatCount does not work!
Here is my anim

23条回答
  •  旧巷少年郎
    2020-11-27 14:30

    Add the following class to your project:

    import android.view.View;
    import android.view.animation.Animation;
    
    public class AnimationRepeater implements Animation.AnimationListener
    {
        private View view;
        private Animation animation;
        private int count;
    
        public AnimationRepeater(View view, Animation animation)
        {
            this.view = view;
            this.animation = animation;
            this.count = -1;
        }
    
        public AnimationRepeater(View view, Animation animation, int count)
        {
            this.view = view;
            this.animation = animation;
            this.count = count;
        }
    
        public void start()
        {
            this.view.startAnimation(this.animation);
            this.animation.setAnimationListener(this);
        }
    
        @Override
        public void onAnimationStart(Animation animation) { }
    
        @Override
        public void onAnimationEnd(Animation animation)
        {
            if (this.count == -1)
                this.view.startAnimation(animation);
            else
            {
                if (count - 1 >= 0)
                {
                    this.animation.start();
                    count --;
                }
            }
        }
    
        @Override
        public void onAnimationRepeat(Animation animation) { }
    }
    

    For infinite loop of your view, do the following:

    Animation a = AnimationUtils(Context, R.anim.animation);
    new AnimationRepeater(View, a).start();
    

    If you want to repeat the animation for N-times only, do the following:

    Animation a = AnimationUtils(Context, R.anim.animation);
    new AnimationRepeater(View, a, int N).start();
    

    N stands for number of repetitions.

提交回复
热议问题