How do I do something when an animation finishes?

AndroidAnimationAndroid 3.1-Honeycomb

Android Problem Overview


I have an ImageView that I use to show progress via an AnimationDrawable. When I want to show my progress spinner, I do this:

animDrawable.start();
ObjectAnimator.ofFloat(view, "alpha", 1.0f).setDuration(300).start();

When I want to hide the spinner, I do this:

ObjectAnimator.ofFloat(view, "alpha", 0.0f).setDuration(300).start();
animDrawable.stop();

However, this has the effect that the animation stops immediately. I would like it to stop only after the ObjectAnimator has completely faded to 0.0 alpha. Is there a way I can setup something along the lines of an "AnimationCompleted" callback?

Android Solutions


Solution 1 - Android

The more modern way of doing this is to use the ViewPropertyAnimator:

view.animate()
    .alpha(0f)
    .withEndAction(new Runnable() {
      @Override
      public void run() {
        // Do something.
      }
    })
    .start();

Or, if you're using RetroLambda:

view.animate()
    .alpha(0f)
    .withEndAction(() -> {
      // Do something.
    })
    .start();

Solution 2 - Android

To your original question about the ObjectAnimator object you can set up an Animator.AnimatorListener object which defines several animation state callbacks. You want to override public void onAnimationEnd(Animator animation)

animation.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    Toast.makeText(VideoEditorActivity.this, "animation ended", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });

Solution 3 - Android

With androidx you can use doOnEnd method which invoked when the animation has ended

val anim = ObjectAnimator.ofFloat(eva_image, View.TRANSLATION_Y, 0f, 500f)
anim.setDuration(500)
anim.doOnEnd { Toast.makeText(this, "Anim End", Toast.LENGTH_SHORT).show() }
anim.start()

Solution 4 - Android

You could also look into postOnAnimation(Runnable)

Link to Docs: postOnAnimation(java.lang.Runnable)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioni_am_jorfView Question on Stackoverflow
Solution 1 - Androidi_am_jorfView Answer on Stackoverflow
Solution 2 - AndroidAaron DancygierView Answer on Stackoverflow
Solution 3 - AndroidAjayView Answer on Stackoverflow
Solution 4 - AndroidProjectDeltaView Answer on Stackoverflow