android - 如何停止动画(来自 ObjectAnimator)

标签 android android-animation

下面是属于我的 Activity 的代码,其中我有一个按钮 (someButton),单击该按钮时,会在同一 Activity 的另一个 View 上启动动画,更具体地说,是一个进度条 View :

// [...]
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();
    }
});
// [...]

现在,在某些时候我可能需要停止该进度条 View 的动画(例如,当用户点击停止按钮时)。我调用了 progressView.clearAnimation() 来停止动画但没有成功。我还注意到 progressView.getAnimation() 返回 null ... 当我将 ObjectAnimator animation 变量设置为 final 并将其移到 someButton.setOnClickListener 之外,以便稍后访问它以停止动画时,我得到以下异常点击 someButton(就像发生的事情 here ):

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!
    }
});
// [...]

这里有什么问题??怎么才能停止那个动画呢???

最佳答案

你可以这样使用:

valueAnimator?.removeAllUpdateListeners()
valueAnimator?.removeAllListeners()
valueAnimator?.end()
valueAnimator?.cancel()
valueAnimator = null

关于android - 如何停止动画(来自 ObjectAnimator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185966/

相关文章:

android - 找不到值类型为 float 的 Button 的 setter 属性旋转

java - 异步启动 Activity 不出现

android - 阿杜伊诺 : HC-06 Module receiving wrong data?

javascript - 在物理 Android 设备上运行 Meteor 移动应用

android - 在android中推动画?

android - 如何以编程方式创建 Activity 转换?

android - 如何逐渐隐藏 Recyclerview 滚动条上的项目

android - 如何获取 TextView 的背景颜色?

android - 如何多次运行同一个异步任务?

android - AnimationDrawable 以编程方式没有动画列表 xml