Animation in changing LayoutParams in LinearLayout

Chrishan picture Chrishan · Mar 14, 2012 · Viewed 21.9k times · Source

In my app there is a LinearLayout which has 0 Layout height. When I click the button this layout height should be LayoutParams.WRAP_CONTENT. This is the code I use in onclicklistner.

LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
slider.setLayoutParams(lp);

I want to animate this. How can I set animation to slider.

Answer

Kai picture Kai · Mar 14, 2012

I think you just want to animate a view from 0 height to its final height, you can do this with a custom Animation:

public class ShowAnim extends Animation {
    int targetHeight;
    View view;

    public ShowAnim(View view, int targetHeight) {
        this.view = view;
        this.targetHeight = targetHeight;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (targetHeight * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth,
            int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

And do this in your code to start the animation:

Animation ani = new ShowAnim(headerView, 100/* target layout height */);
ani.setDuration(2000/* animation time */);
headerView.startAnimation(ani);