以下是我的活动代码,其中有一个按钮(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!
}
});
// [...]
我在这里做错了什么??怎么停止那个动画???
cancel
和end
方法。 - pskink