Below is the code belonging to my activity where I have a button (someButton) which, when clicked, starts an animation on another view, more specifically, a progressbar view, on that same activity:
// [...]
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();
}
});
// [...]
Now, at some point I may need to stop that progress bar view's animation (when the user taps a stop button, for example). I called progressView.clearAnimation()
to stop the animation but got no success. I have also noticed that progressView.getAnimation() returns null...
And when I make ObjectAnimator animation
variable final and move it outside the someButton.setOnClickListener
, so that I can access it later to stop the animation, I get the following exception when I tap on someButton (just like what happens 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)
[...]
And the code that throws that exception is:
// [...]
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!
}
});
// [...]
What am doing wrong here?? How can one stop that animation???