问题
I use the ObjectAnimator API (android.animation.ObjectAnimator) to animate a button once it's clicked (v is the Button):
ObjectAnimator animator = ObjectAnimator.ofFloat(v, "rotationY", 360f);
animator.setDuration(5000);
animator.start();
When I test this on the emulator, it works for the first click (button rotates). But when I click the button again (the fragment is not destroyed etc. after the first click), I don't see any animation on the emulator (the emulator isn't the fastest, but with 5 seconds I should see something).
Do I need to destroy/close something after the first animation or what am I missing? Does anyone have a hint or can reproduce this?
Thanks in advance, Martin
回答1:
The second time you will try to animate from 360.0f to 360.0f. Change your call to ofFloat() to:
ObjectAnimator.ofFloat(v, "rotationY", 0.0f, 360.0f)
回答2:
To elaborate on Romain's answer, the result of the single-value factory constructor is animation that will run from whatever the current value is to the value specified in the parameters. In your case, the object had a value of 0 to begin with an animated (the first time) to a value of 360. The second time it ran, it animated from the current value (360) to the specified value (360). Not much of an animation.
The fix is as above: hard-code both the start and end values for the animator. Alternatively, you can reset the value back to 0 when the animation finishes by implementing the AnimatorListener.onAnimationEnd method and resetting it when the animation finishes:
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
v.setRotationY(0);
}
});
来源:https://stackoverflow.com/questions/5317332/android-objectanimation-only-started-once