Android GridLayout Equal Column Widths

Boulder Keith picture Boulder Keith · Mar 14, 2014 · Viewed 34.3k times · Source

Is it really not possible to easily force equal column widths in an Android GridLayout? Trying the obvious layout...

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="4"
    android:rowCount="8"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_gravity="center"
        android:text="Button 1" />
    <Button
        android:id="@+id/button2"
        android:layout_gravity="center"
        android:text="Button 2" />
    <Button
        android:id="@+id/button3"
        android:layout_gravity="center"
        android:text="Button 3" />
    <Button
        android:id="@+id/button4"
        android:layout_gravity="center"
        android:text="Button 4" />

</GridLayout>

... leaves the rightmost button centered in a column that is clearly wider than the other three. (Play with the button text and you can easily get worse examples.)

I read the Android documentation regarding excess space distribution in GridLayouts, but it seems so obvious that even column widths are often (any maybe even typically) wanted in a situation like this that I have to believe I'm missing something obvious/easy.

Answer

Al Polden picture Al Polden · Jul 15, 2014

Use a table layout instead and specify stretch columns.

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textViewLeaveRemainingDescription"
    android:stretchColumns="0,1">

    <TableRow>
        <Button
            android:id="@+id/button1"
            android:layout_gravity="center"
            android:text="Button 1" />

        <Button
            android:id="@+id/button3"
            android:layout_gravity="center"
            android:text="Button 3" />
    </TableRow>

    <TableRow>
        <Button
            android:id="@+id/button2"
            android:layout_gravity="center"
            android:text="Button 2" />

        <Button
            android:id="@+id/button4"
            android:layout_gravity="center"
            android:text="Button 4" />
    </TableRow>
</TableLayout>