Horizontally center Views inside Android GridLayout

RealCasually picture RealCasually · Sep 12, 2012 · Viewed 14.5k times · Source

We are writing an app targeting ICS+ and believe a GridLayout is the best layout paradigm, but it seems very little has been written about it, and we are having some alignment issues.

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/row_background"
    android:rowCount="1"
    android:columnCount="3"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:useDefaultMargins="true"
    android:background="@drawable/list_item_bg">

    <ImageView
        android:id="@+id/visibilityIcon"
        android:layout_row="0"
        android:layout_column="0"
        android:src="@drawable/visibility_icon" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <ImageView
        android:id="@+id/windIcon"
        android:layout_row="0"
        android:layout_column="1"
        android:src="@drawable/wind_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <ImageView
        android:id="@+id/crosswindIcon"
        android:layout_row="0"
        android:layout_column="2"
        android:src="@drawable/cloud_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</GridLayout>

However, the left 2 icons remain left-aligned, and the right-most icon centers with the remaining space.

Essentially what we need to do is specify the size of each column to be 1/3 (since 3 columns) of the total screen size. I thought this is what GridLayout did, but it appears 'wrap_content' causes this behavior (makes sense), but 'match_parent' causes the first column to fill the entire screen, rather than fill its cell which is the behavior I would have expected.

We seem to have tried every combination of gravity, layout_gravity, etc., but either we fundamentally are doing something wrong, or have found a limitation of the GridLayout.

Thanks for your help!

Answer

Tobias Ritzau picture Tobias Ritzau · Sep 12, 2012

Only one row and one column is allowed to grow in a GridLayout, and that is the one with gravity along that axis. If more than one row or column specify gravity only one will get it (if I remember it is the "last" one). Choose another layout or write your own. If you only want a row with equally split icons you can use a LinearLayout where the widths of the components are 0px and the weight are all the same, e.g. 1.