Skip to content Skip to sidebar Skip to footer

Dynamically Change Column Number In Android Gridview?

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

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


Solution 2:

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!)


Post a Comment for "Dynamically Change Column Number In Android Gridview?"