I use the below grid layout with layout_columnWeight
and layout_rowWeight
to centralize my view in the grid cell.
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>
Instead of Using
android:layout_columnWeight="1"
android:layout_rowWeight="1"
Use:
app:layout_columnWeight="1"
app:layout_rowWeight="1"
This will help.
For beginners like me @Amir Ziarati's answer is on point. you need to add this line in your build.gradle (Module:app)
implementation 'com.android.support:gridlayout-v7:26.1.0'
Like this
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:gridlayout-v7:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
And then use
<android.support.v7.widget.GridLayout>
...</android.support.v7.widget.GridLayout>