Home » Android » android – How to stop animation at end of cycle?

android – How to stop animation at end of cycle?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have an ImageView that I’m rotating for use as a loading animation. Once my data is loaded, I try to stop the animation, but instead of cycling to the end and then stopping, the animation goes to a halfway point, then stops, and then the image snaps back to its original state, which looks pretty ugly.

Here is what I’ve tried:

Option 1:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null) {
    iv.clearAnimation();
}

Option 2:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null && iv.getAnimation() != null) {
    iv.getAnimation().cancel();
}

Option 3:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null && iv.getAnimation() != null) {
    iv.getAnimation().setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            animation.cancel();

        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }
    });
}

The end result is the same in all three cases. How do I rotate the image and have it end up back where it started?

Edit:

Some further information: My rotation animation:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />

How I start the animation:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
How to&Answers:

Set the animation repeatcount to infinite before you start it, then when the action finishes, set the repeatcount of the animation to 0. The animation will finish the current loop and the stop without the jump that you want to avoid.

//How you start
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
          rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);

//You do your stuff while it spins
...

//You tell it not to repeat again
rotation.setRepeatCount(0);

It’s important that you first set it to Animation.INFINITE (or -1 since they do the same) and then to 0, if you set it to 1000 for instance, then it wont stop for some reason according to my testing.

Answer:

You can use rotation.setFillAfter(true);

Answer:

iv.clearAnimation(); to stop the animation