I use the below grid layout with layout_columnWeight
and layout_rowWeight
to centralize my view in the grid cell.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<GridLayout
android:id="@+id/container_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2"
android:rowCount="3"
android:orientation="horizontal">
<View
android:id="@+id/view_red"
android:layout_height="100dp"
android:layout_width="100dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:layout_gravity="center"
android:background="#ff0000"
android:layout_row="0"
android:layout_column="0" />
<View
android:id="@+id/view_green"
android:layout_height="100dp"
android:layout_width="100dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:layout_gravity="center"
android:background="#00ff00"
android:layout_row="0"
android:layout_column="0" />
<View
android:id="@+id/view_blue"
android:layout_height="100dp"
android:layout_width="100dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:layout_gravity="center"
android:background="#0000ff"
android:layout_row="0"
android:layout_column="0" />
</GridLayout>
</RelativeLayout>
But they are for v21 and above only. How to support layout_columnWeight
and layout_rowWeight
feature in pre API 21?
the version of GridLayout in support library is backward compatible and supports weights as mentioned here:
https://developer.android.com/reference/android/support/v7/widget/GridLayout.html
so you just need to add compile 'com.android.support:gridlayout-v7:23.1.1'
to your build.gradle file and use support gridlayout instead ;)
use it like below (android.support.v7.widget.GridLayout
) in your layout xml file:
<android.support.v7.widget.GridLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="3"
app:orientation="horizontal">
<View
android:id="@+id/view_red"
android:layout_height="100dp"
android:layout_width="100dp"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
app:layout_gravity="center"
android:background="#ff0000"
app:layout_row="0"
app:layout_column="0" />
</android.support.v7.widget.GridLayout>