How to set a column width relative with the GridLayout width?

54 Views Asked by At

I want to set a column width to a quarter width of his parent (the GridLayout), even if there is a single column in the row.

<GridLayout
    android:id="@+id/widget_place"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="3"
    android:layout_marginVertical="10dp"
    android:orientation="horizontal"
    android:columnCount="3"
    android:columnOrderPreserved="false"
    >
    <Button
        android:id="@+id/btn"
        android:text="card1"
        android:layout_columnSpan="1"
        android:layout_columnWeight="4"
        android:layout_gravity="clip_horizontal"
        />
</GridLayout>
1

There are 1 best solutions below

0
Aniket kumar On

You can set the width of a column in a GridLayout to a quarter of the parent's width by using the android:layout_width attribute and setting it to "0dp" and the android:layout_weight attribute to "0.25". This tells the column to take up 25% of the remaining space in the parent GridLayout.

<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="1">
<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.25"
    android:text="Column 1" />
</GridLayout>

This will make the column width 1/4 of the parent's width, even if there is only one column in the row.