Saad Farooq
Saad Farooq

Reputation: 13402

Reverse AnimatorSet

Is there a way to run an AnimatorSet in reverse on Android? The ValueAnimator API does provide a reverse method on the individual animators but not on a set of animators.

Upvotes: 3

Views: 5266

Answers (3)

EyesClear
EyesClear

Reputation: 28417

The reverse() method has been added in API 26:

Plays the AnimatorSet in reverse. If the animation has been seeked to a specific play time using setCurrentPlayTime(long), it will play backwards from the point seeked when reverse was called. Otherwise, then it will start from the end and play backwards. This behavior is only set for the current animation; future playing of the animation will use the default behavior of playing forward.

Note: reverse is not supported for infinite AnimatorSet.

Upvotes: 1

Kevin Crain
Kevin Crain

Reputation: 1935

You can take the initial input values from i.e ValueAnimator.ofFloat(0, 1) and switch them around with yourAnimator.setFloatValues(1, 0) before calling yourAnimatorSet.start() when you want to reverse animation

Upvotes: 1

Travis
Travis

Reputation: 2026

If your AnimatorSet is being played sequentially then you could use the method mentioned by @blackbelt:

public static AnimatorSet reverseSequentialAnimatorSet(AnimatorSet animatorSet) {
    ArrayList<Animator> animators = animatorSet.getChildAnimations();
    Collections.reverse(animators);

    AnimatorSet reversedAnimatorSet = new AnimatorSet();
    reversedAnimatorSet.playSequentially(animators);
    reversedAnimatorSet.setDuration(animatorSet.getDuration());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        // getInterpolator() requires API 18
        reversedAnimatorSet.setInterpolator(animatorSet.getInterpolator());
    }
    return reversedAnimatorSet;
}

The caveat being that this only works for simple sequential animations as any dependencies setup in the original AnimatorSet will be lost. Also, if an interpolator was used on the AnimatorSet it will only carry over on API 18 or newer (per method mentioned above, you could alternatively manually add the interpolator back to the new reversed animator set).

The individual animations within the AnimatorSet will not play in reverse, if that is desirable then you'll also have to iterate over the animations of the AnimatorSet and set a ReverseInterpolator on each, see answer to Android: Reversing an Animation.

Upvotes: 4

Related Questions