Search code examples
androidxmlandroid-linearlayoutgrid-layoutandroid-relativelayout

GridLayout not evenly spacing children throughout screen


I have a GridLayout and inside it are 6 LinearLayout children. Inside those are buttons and other things.

In Android Studio it looks fine, however on an actual device (and even emulator) it does not space evenly. Here is a picture of what is happening. enter image description here

<RelativeLayout <!--main layout stuff-->
>

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rowCount="4"
    android:columnCount="2">
        <!--
           there are six of these inside the grid layout
        -->
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1">

            <ImageButton
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/button"
                android:src="@drawable/button"
                android:layout_gravity="center"/>
        </LinearLayout>

     </GridLayout>

</RelativeLayout>

Solution

  • The issue with this is that android:layout_columnWeight and android:layout_rowWeight are new in Lollipop and so aren't supported before that. You can use GridLayout from the support library and app:layout_columnWeight/app:layout_rowWeight to get these features for older android devices.

    <android.support.v7.widget.GridLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:rowCount="4"
        app:columnCount="2">
            <!--
               there are six of these inside the grid layout
            -->
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:layout_columnWeight="1"
                app:layout_rowWeight="1">
    
                <ImageButton
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:id="@+id/button"
                    android:src="@drawable/button"
                    android:layout_gravity="center"/>
            </LinearLayout>
    
    </GridLayout>