CL So
CL So

Reputation: 3769

How to auto layout_width / layout_height in android?

I want something like this

<LinearLayout android:layout_width="auto"
              android:layout_height="match_parent"
              android:background="#fff"
              android:orientation="vertical">
</LinearLayout>

The height of parent may be dynamic

If height of parent is 100dp, then the width will be 100dp

If height of parent is 200dp, then the width will be 200dp

Upvotes: 0

Views: 850

Answers (1)

doubleA
doubleA

Reputation: 2466

I do not think that android has this by default. You can however create your own Linear layout that does this.

public class MyLinearLayout extends LinearLayout {
    public MyLinearLayout(Context context) {
        super(context);
    }

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(height, height);
    }
}

Please note that you might have problems if the width of the screen is not wide enough to display your layout at your desired height. In xml just set your width to match_parent as well.

Upvotes: 1

Related Questions