Dynamically animate a layout

Neoh picture Neoh · May 4, 2013 · Viewed 7.7k times · Source

I have to implement a (child) layout translate animation programmatically because the distance to translate is determined at runtime. I have set the following translate animation

    TranslateAnimation tanim = new TranslateAnimation(
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 100);

to slide down the layout, for example.

Problem 1: This layout will snap back to its original position after the animation finishes. Is there anything I should set to maintain its position? I suspect this is caused by the layout being moved out of the parent layout (parent layout has parameter layout_width="wrap_content"). If this is the case how can I adjust the parent layout to accomodate the child layout change?

Problem 2: Do I have to provide a custom interpolator class to achieve a decelerating effect? If yes, do you know where can I find an example? In xml I can do this

android:interpolator="@android:anim/accelerate_interpolator"

Is there an equivalent Android code to achieve the accelerate/decelerate effect programmatically?

Answer

FoamyGuy picture FoamyGuy · May 4, 2013

to keep the position after the animation you need to use the fillAfter attribute. And yes there are Accelerate and Decelerate interpolater classes within the public APIs

TranslateAnimation tanim = new TranslateAnimation(
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 0.0f,
        TranslateAnimation.ABSOLUTE, 100);
tanim.setFillAfter(true);
tanim.setInterpolater(new DecelerateInterpolator());
//tanim.setInterpolater(new AccelerateInterpolator());

See the Animation docs for info about fillAfter and the Interpolator docs for a list of the built in Interpolator objects within the system.