12

I have a TranslateAnimation on my class. The animation starts automatically.

I set button that if it is clicked, the animation will be canceled (animation.cancel();).

I also set an AnimationListener for my class. If my animation ends, I will start a new Activity (you go to the menu).

public void onAnimationEnd(Animation animation) {
    startActivity(new Intent(Class.this, Class2.class));
}

My app is relying on that the user has to click the button before the animation ends. The problem is that animation.cancel(); is admitted as the end of the animation.

How to cancel the animation in the other way that was not counted as the end of the animation? Is that possible?

Thanks in advance!

Ganjira
  • 966
  • 5
  • 16
  • 32

2 Answers2

37

Once the animation is cancelled, you can remove the listener thus preventing onAnimationEnd from being called:

@Override
public void onAnimationCancel(Animator animation) {
  animation.removeAllListeners();
}
Simas
  • 43,548
  • 10
  • 88
  • 116
  • 1
    Nice approach! However, `animation.removeListener(this)` would prevent you from removing other listeners that may want to listen to cancel/animationEnd events. – alexbchr Jun 06 '18 at 19:11
  • @alexbchr `animation.removeListener(this)` didn't work for me, `onAnimationEnd` was still being called. `animation.removeAllListeners()` did the trick tho – Sfseyhan Mar 02 '23 at 10:00
  • worked for me too, but also I was calling `animation.cancel()` before it, I moved cancel call after `removeAllListeners()`, it worked – nasibeyyubov Aug 27 '23 at 11:07
4

animation.cancel() is calling the animation listener as API documentation describes:

Cancelling an animation invokes the animation listener, if set, to notify the end of the animation. If you cancel an animation manually, you must call reset() before starting the animation again.

If you want different behaviour on cancel() and onAnimationEnd() i would suggest a boolean variable, which can be set on button click, and onanimationend checks whether it is true.

abbath
  • 2,444
  • 4
  • 28
  • 40