Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid View auto number of columns depending on screen size

I am using Gridview and I want to show some pictures in it. I want my grid view to look good in all sizes of screen. I mean I am developing my app for different android devices such as Samsung Galaxy Grand which is normal device , Samsung tab 4 which is 7 inch device and in the end Samsung tab 10 which is 10 inch device.

So I want my grid view to take auto number which looks good on device such as I want 4 column on Samsung Tablet 10 inch and with same ration 3 or two in 7 inch and same like this on other devices.

So what I have done so far is simple thing , made an array for Images and set adapter to the gridview that is simple code and that has nothing o do with my problem so I am not sharing that code What I have with its desing is in xml so my xml looks like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="250dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="50dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

</LinearLayout>

So please help me out in this problem. How can I make the number of columns to auto fit the screen width. ??

like image 662
Coas Mckey Avatar asked Sep 11 '15 07:09

Coas Mckey


1 Answers

Just use different number of columns for different screen sizes - override value in different values folder (small, normal, large, xlarge), see documentation.

Example:

Activity or fragment:

<GridView
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="@integer/column_count"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:verticalSpacing="50dp"
    />

Item:

<ImageView
    android:id="@+id/image"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

values/integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="column_count">2</integer>
</resources>

values-large/integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="column_count">3</integer>
</resources>

values-xlarge/integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="column_count">4</integer>
</resources>
like image 136
Oleksandr Avatar answered Oct 22 '22 02:10

Oleksandr