Android GridLayout center horizontally

Tomasz picture Tomasz · Jul 24, 2014 · Viewed 46.8k times · Source

I'm trying to create a GridLayout with 2 columns which will be centered.

My avtual design is:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    custom:rowCount="4"
    custom:columnCount="2"
    android:orientation="horizontal">
    <TimeTableKeeper.Tile
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:gravity="top|left"
        android:background="#00FF00"
        custom:color="green"
        custom:layout_row="0"
        custom:layout_column="0" />
    <TimeTableKeeper.Tile
        android:layout_width="75dp"
        android:gravity="top|left"
        android:layout_height="75dp"
        android:background="#00FF00"
        custom:color="blue"
        custom:layout_row="0"
        custom:layout_column="1" />
</GridLayout>

And it looks like:

And I would like to have this buttons in the center and perfectly with spacing between them.

Is it possible?

--EDIT:

I have also tried putting it into LinearLayout, without results:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <GridLayout xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        custom:rowCount="4"
        custom:columnCount="2"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_gravity="center">
        <TimeTableKeeper.Tile
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:background="#00FF00"
            custom:color="green"
            custom:layout_row="0"
            custom:layout_column="0" />
        <TimeTableKeeper.Tile
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:background="#00FF00"
            custom:color="blue"
            custom:layout_row="0"
            custom:layout_column="1" />
    </GridLayout>
</LinearLayout>

Answer

razz picture razz · Nov 22, 2015

Make the grid wrap around its content horizontally with layout_width="wrap_content" and set it's layout_gravity to center:

<GridLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    // ......
    >