Android stop button animation on an event
I am trying to animate a button. The animation is working but I am not able to stop it.
First I defined a property in the class
private ObjectAnimator animatorBtn;
Then when an event ocur inside a method I start the animation
@Override
public void writeMessage(final Message message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (myBtn.getVisibility() == View.VISIBLE && messageView.getVisibility() != View.VISIBLE) {
myBtn.setBackground(context.getResources().getDrawable(R.drawable.red_round_button));
animatorBtn = ObjectAnimator.ofFloat(myBtn, "translationY", -100f, 0f);
animatorBtn.setDuration(1000);//1sec
animatorBtn.setInterpolator(new BounceInterpolator());
animatorBtn.setRepeatCount(ValueAnimator.INFINITE);
animatorBtn.start();
}
messageView.writeViewMessage(message);
}
});
}
On another event I am trying to stop it. but is not working
@OnClick(R.id.my_btn)
void onClickMyBtn() {
runOnUiThread(new Runnable() {
@Override
public void run() {
myBtn.setBackground(context.getResources().getDrawable(R.drawable.green_round_button));
if (animatorBtn != null) {
animatorBtn.cancel();
}
}
});
}
thank you