Home » Android » Dynamically change column number in android gridview?

Dynamically change column number in android gridview?

Posted by: admin June 15, 2020 Leave a comment

Questions:

My application display the image icon in gridview in landscape orientation.For that i use the xml as

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="4"
    android:columnWidth="100px"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

For portrait orientation i want to display only two image icon in gridview column.How to do it?.

How to&Answers:

By using adaptive resources: make sure in resources folder /res you have the following folders: values-land and values-port. In both of those folders add a resource file, let’s call it integers.xml.

In /values-land/integers.xml you will have at least:

<resources>
    <item name="grid_rows" type="integer">4</item>
</resources>

while for values-port/integers.xml:

<resources>
    <item name="grid_rows" type="integer">3</item>
</resources>

The layout changes to:

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="100px"
    android:gravity="center"
    android:numColumns="@integer/grid_rows"
    android:stretchMode="columnWidth" />

Note the presence of @integer/grid_rows

Answer:

I had this issue and gunar’s answer was very helpful but I think I can add some more details. If in AndroidStudio, set directory view to “Project” (so that you will be able to see your new directories) and right click on “res” to create new resource directory. Make two new directories, “values-port” and “values-land” each as type value.

Then, in values-land, add an integer item:

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

and in values-port, add an integer item:

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

Now in your gridview layout, instead of hard coding your numColumn:

<GridView
       android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:numColumns="@integer/columns"
        android:columnWidth="100px"
        android:stretchMode="columnWidth"
        android:gravity="center"/> 

This is essentially gunar’s solution (thank you gunar!) but it adds some details I discovered along the way. For instance, I couldn’t see the res directories I was making until I changed to Project view and there is already an integer resource type so we don’t need to declare the columns as item and then set type to integer. (BTW: I am loving the Android XML tool!)