3

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.

Saad Farooq
  • 13,172
  • 10
  • 68
  • 94
  • Just a quick thought, not tested or validated: You could probably use a custom `Interpolator` that runs backwards, i.e. returns something like `1.0 - input`. See http://developer.android.com/reference/android/animation/AnimatorSet.html#setInterpolator%28android.animation.TimeInterpolator%29 – tiguchi Oct 08 '15 at 20:37
  • you could use `getChildAnimations()` and reverse the collection, and add it again – Blackbelt Oct 08 '15 at 20:37

3 Answers3

4

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.

Community
  • 1
  • 1
Travis
  • 1,926
  • 1
  • 19
  • 26
1

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

Kevin Crain
  • 1,905
  • 1
  • 19
  • 28
1

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.

Community
  • 1
  • 1
EyesClear
  • 28,077
  • 7
  • 32
  • 43