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

后端 未结 7 1073
轮回少年
轮回少年 2020-11-29 16:52

I need to stop a running translate animation. The .cancel() method of Animation has no effect; the animation goes until the end anyway.

How

7条回答
  •  不知归路
    2020-11-29 17:28

    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);
    

提交回复
热议问题