Reversing an Animation

Solution 1:

No, sadly you cannot do it with the Animation object. But you can simulate it using an interpolator that will inverse the animation:

package com.example.android;

import android.view.animation.Interpolator;

public class ReverseInterpolator implements Interpolator {
    @Override
    public float getInterpolation(float paramFloat) {
        return Math.abs(paramFloat -1f);
    }
}

Then on your animation you can set your new interpolator:

myAnimation.setInterpolator(new ReverseInterpolator());

Solution 2:

If you are using Object or ValueAnimator to animate the view, you can simply do

ValueAnimator myAnimator = new ValueAnimator();  
myAnimator.reverse()

Documentation can be found here.

Solution 3:

Based on pcans idea, you can reverse any interpolator, not just linear.

class ReverseInterpolator implements Interpolator{
    private final Interpolator delegate;

    public ReverseInterpolator(Interpolator delegate){
        this.delegate = delegate;
    }

    public ReverseInterpolator(){
        this(new LinearInterpolator());
    }

    @Override
    public float getInterpolation(float input) {
        return 1 - delegate.getInterpolation(input);
    }
}

Usage

ReverseInterpolator reverseInterpolator = new ReverseInterpolator(new AccelerateInterpolator())
myAnimation.setInterpolator(reverseInterpolator);

Solution 4:

I have a similar approach to pcans buts slightly different. It takes an Interpolator and will effectively pass out values that would be the same as using the passed in Interpolator normally and then in REVERSE mode. Saves you having to think about the buggy implementations of Animation.REVERSE across Android. See the code here

public class ReverseInterpolator implements Interpolator {

    private final Interpolator mInterpolator;

    public ReverseInterpolator(Interpolator interpolator){
        mInterpolator = interpolator;
    }

    @Override
    public float getInterpolation(float input) {
        return mInterpolator.getInterpolation(reverseInput(input));
    }

    /**
     * Map value so 0-0.5 = 0-1 and 0.5-1 = 1-0
     */
    private float reverseInput(float input){        
        if(input <= 0.5)
            return input*2;
        else
            return Math.abs(input-1)*2;        
    }
}