How to stop an animation (cancel() does not work) How to stop an animation (cancel() does not work) android android

How to stop an animation (cancel() does not work)


Call clearAnimation() on whichever View you called startAnimation().


On Android 4.4.4, it seems the only way I could stop an alpha fading animation on a View was calling View.animate().cancel() (i.e., calling .cancel() on the View's ViewPropertyAnimator).

Here's the code I'm using for compatibility before and after ICS:

public void stopAnimation(View v) {    v.clearAnimation();    if (canCancelAnimation()) {        v.animate().cancel();    }}

... with the method:

/** * Returns true if the API level supports canceling existing animations via the * ViewPropertyAnimator, and false if it does not * @return true if the API level supports canceling existing animations via the * ViewPropertyAnimator, and false if it does not */public static boolean canCancelAnimation() {    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;}

Here's the animation that I'm stopping:

v.setAlpha(0f);v.setVisibility(View.VISIBLE);// Animate the content view to 100% opacity, and clear any animation listener set on the view.v.animate()    .alpha(1f)    .setDuration(animationDuration)    .setListener(null);


If you are using the animation listener, set v.setAnimationListener(null). Use the following code with all options.

v.getAnimation().cancel();v.clearAnimation();animation.setAnimationListener(null);