Android GridLayout: How to align child view to right with its column width proportional

90 Views Asked by At

I have a Grid with two columns, each with a label. I want the label on the 2nd column to align to the right:

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    app:columnCount="2">

    <TextView
        android:text="Cell 0"
        app:layout_column="0"
        app:layout_columnWeight="1"
        android:background="#FF0000" />

    <TextView
        android:text="Cell 1"
        app:layout_column="1"
        app:layout_columnWeight="1"
        app:layout_gravity="right"
        android:background="#0000FF"/>

</androidx.gridlayout.widget.GridLayout>

enter image description here

How can I make the 1st column to be equal to the 2nd column, like in the mockup below?

enter image description here

I tried setting android:gravity="right" but it solves half of the problem. Columns are equal in width, but the blue label fills the column:

        <TextView
            android:text="Cell 1"
            app:layout_column="1"
            app:layout_columnWeight="1"
            android:gravity="right"
            android:background="#0000FF"/>

enter image description here

The way GridLayout computes the width of a proportionally sized column is very weird. It appears it takes into account the width of the child view. The documentation does not help in describing how the layout_columnWeight works exactly.

1

There are 1 best solutions below

5
Omkar On

try below code this may result what you expected

 <androidx.gridlayout.widget.GridLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#00FF00"
    app:columnCount="2"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:text="Cell 0"
        android:layout_width="0dp"
        app:layout_column="0"
        app:layout_columnWeight="1"
        android:background="#FF0000" />

    <LinearLayout
        app:layout_column="1"
        android:layout_width="0dp"
        app:layout_columnWeight="1"
        android:gravity="right">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cell 1"
            android:background="#0000FF"/>
    </LinearLayout>

</androidx.gridlayout.widget.GridLayout>

enter image description here