Reputation: 2120
What I need is an infinitely repeatable AnimatorSet
(composed of 2 sequential animations
) but also a way to stop these animations
in a safe way (i.e. the final state is same as starting state). The stop would happen for example by tapping on the screen.
Major problem I had was when I tried stopping by calling either animatorSet.end()
or cancel()
, the animation was stopping either midway or finishing the first of the animations (hence not returning to original state).
I found a solution, which really is a mix of a number of different solutions found on SO.
IMPORTANT: The two sequential animations together create a graceful loop, such that animation1
takes a button
slowly to the right, while animation2
returns it to the left more rapidly. This is why I need the stop to end gracefully, such that it finishes animation1
and animation2
, whatever the state is when I want to stop it.
Upvotes: 1
Views: 824
Reputation: 2120
To create a repeatable AnimatorSet
:
animatorSet = new AnimatorSet();
animatorSet.play(animation1).after(animation2);
animatorSet.addListener(new AnimatorListenerAdapter() {
boolean isCancelled;
@Override
public void onAnimationEnd(Animator animation) {
if (!isCancelled) {
animatorSet.start();
}
}
@Override
public void onAnimationCancel(Animator animation) {
this.isCancelled = true;
}
});
animatorSet.start();
Now the below method stopAnimation()
you would call from your onClickListener
or whatever you need to listen for to stop the animation
(bear in mind animatorSet
has to be accessible, make it a field for example).
public void stopAnimation(Context context){
guideAnimationSet.removeAllListeners();
In the end I didn't need any cancel()
or end()
.
This actually makes sense: once I remove the listener
, the animatorSet
will finish the current animations
and then won't be able to start it again since the listener
for repeating is gone.
Hope it helps someone!
Upvotes: 2