P Ravikant P Ravikant - 1 year ago 93
Java Question

How to animate the width and height of a Layout?

I have a

which is expanded to full screen by hiding all other layouts and views on
. There is a

I want to apply custom animation on this. The size should should increase slowly (like in 500 milli seconds).

But I doubt is it possible? Thanks.

Here is what I am doing

private void expandView (int viewId) {
RelativeLayout relativeLayout = (RelativeLayout) ((LinearLayout) view.findViewById(viewId)).getParent();
ViewGroup.MarginLayoutParams rlMargin = (ViewGroup.MarginLayoutParams) relativeLayout.getLayoutParams();
rlMargin.setMargins(0, 0, 0, 0);
LinearLayout linearLayout = (LinearLayout) relativeLayout.getParent();

is the id of the
I am clicking. This function is called from

Answer Source

Sure that is possible.

Simply write your own custom-animation and modify the LayoutParams of your animated view. In this example, the animation animates the height of the animated View. Of course, animating the width is also possible.

This is how it could look like:

public class ResizeAnimation extends Animation {

    private int startHeight;
    private int deltaHeight; // distance between start and end height
    private View view;

     * constructor, do not forget to use the setParams(int, int) method before
     * starting the animation
     * @param v
    public ResizeAnimation (View v) {
        this.view = v;

    protected void applyTransformation(float interpolatedTime, Transformation t) {

        view.getLayoutParams().height = (int) (startHeight + deltaHeight * interpolatedTime);

     * set the starting and ending height for the resize animation
     * starting height is usually the views current height, the end height is the height
     * we want to reach after the animation is completed
     * @param start height in pixels
     * @param end height in pixels
    public void setParams(int start, int end) {

        this.startHeight = start;
        deltaHeight = end - startHeight;

     * set the duration for the hideshowanimation
    public void setDuration(long durationMillis) {

    public boolean willChangeBounds() {
        return true;

In code, create a new Animation and apply it to the RelativeLayout that you want to animate:

RelativeLayout relativeLayout = (RelativeLayout) ((LinearLayout) view.findViewById(viewId)).getParent();

// getting the layoutparams might differ in your application, it depends on the parent layout
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();

ResizeAnimation a = new ResizeAnimation(relativeLayout);

// set the starting height (the current height) and the new height that the view should have after the animation
a.setParams(lp.height, newHeight);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download