如何停止一个来自ObjectAnimator的动画?

3
以下是我的活动代码,其中有一个按钮(someButton),当点击它时,在同一活动中的另一个视图上启动了动画,更具体地说,是进度条视图:
// [...]
someButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        ObjectAnimator animation = ObjectAnimator.ofInt(progressView, "progress", 0, 2000);
        animation.setDuration(2000);
        animation.setInterpolator(new DecelerateInterpolator());
        animation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // some code to execute when the animation ends
            }
        });
        animation.start();
    }
});
// [...]

现在,当用户点击停止按钮时,我可能需要停止进度条视图的动画。我调用了progressView.clearAnimation()来停止动画,但没有成功。我还注意到progressView.getAnimation()返回null... 当我将ObjectAnimator animation变量设置为final并将其移出someButton.setOnClickListener,以便稍后访问以停止动画时,当我点击someButton时会出现以下异常(就像这里所发生的一样):

java.lang.NullPointerException
   at android.animation.PropertyValuesHolder.setupSetterAndGetter(PropertyValuesHolder.java:505)
   at android.animation.ObjectAnimator.initAnimation(ObjectAnimator.java:487)
   at android.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:517)
   at android.animation.ValueAnimator.start(ValueAnimator.java:936)
   at android.animation.ValueAnimator.start(ValueAnimator.java:946)
   at android.animation.ObjectAnimator.start(ObjectAnimator.java:465)
   at android.animation.AnimatorSet$1.onAnimationEnd(AnimatorSet.java:579)
   at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1056)
   at android.animation.ValueAnimator.access$400(ValueAnimator.java:50)
[...]

引发该异常的代码是:

// [...]

final ObjectAnimator animation = ObjectAnimator.ofInt(progressView, "progress", 0, 2000);
animation.setDuration(2000);
animation.setInterpolator(new DecelerateInterpolator());
animation.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        // some code to execute when the animation ends
    }
});

someButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        animation.start();// NPE occurs here!
    }
});
// [...]

我在这里做错了什么??怎么停止那个动画???


请查看 cancelend 方法。 - pskink
4个回答

2
您可以使用以下方法:
valueAnimator?.removeAllUpdateListeners()
valueAnimator?.removeAllListeners()
valueAnimator?.end()
valueAnimator?.cancel()
valueAnimator = null

0

试一下这个

anim.cancel();
anim.end();
anim.removeAllListeners();

0

首先,您可以查看此链接以获取更好的示例。

我还建议您不要停止动画(除非您使用了Extended view、handlers with postDelay和thread sleeps来正确实现它。如果某些逻辑已完成,请删除视图/打开另一个屏幕,特别是如果是progressView,则无需显示但不旋转,只需删除其可见性。

祝你好运


0

尝试:animation.setCurrentPlayTime(0);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接