Search code examples
androidandroid-layoutandroid-xmlandroid-gridlayout

Android Grid Layout - Even distribution of cells


I am using Grid layout to show custom views on the screen. I need to show these buttons equally spaced horizontally to fill and fit the screen. If X number can be accommodated in row, then move rest to another row. Add new dynamic views in similar fashion.

Similar to following image on Nexus 5 enter image description here

But when I check the ui for smaller screens columns 2 and 3 are gone enter image description here

How can I achieve consistent and even distribution of icons in Grid Layout?

Code Used :

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:columnCount="3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:paddingBottom="7dp"
android:paddingRight="3dp"
tools:context=".MainActivityFragment">

<com.custom.myview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_columnWeight="1"
    android:layout_margin="2dp"/>

<com.custom.myview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_columnWeight="1"
    android:layout_margin="2dp"/>

<com.custom.myview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_columnWeight="1"
    android:layout_margin="2dp"/>

<com.custom.myview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_columnWeight="1"
    android:layout_margin="2dp" />


Solution

  • I got it working and was able to adapt the columns based on screen size by using

    <integer name="column_numbers">3</integer>
    

    or

    <integer name="column_numbers">2</integer>
    

    in different values folders like values-normal-hdpi or values-normal-xxhdpi

    In my layout file add android:columnCount="@integer/column_numbers" to fetch the correct number of columns for respective screen size.