下面是属于我的 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/