Dynamically change column number in gridview?

My application displays the image icon in gridview in landscape orientation. For this, I use 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 icons in the gridview column. How to do it?.

+7
android gridview
source share
2 answers

Using adaptive resources: make sure that the following folders are in the /res resources folder: values-land and values-port . In both folders, add a resource file, call integers.xml on it.

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 will change 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

+18
source share

I had this problem and the gunar answer was very helpful, but I think I can add some details. If in AndroidStudio, set the directory view to "Project" (so you can see your new directories) and right-click "res" to create a new resource directory. Make two new directories, "port-values" and "ground-values" as the type value.

Then in value-land add an integer element:

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

and in the port value add an integer element:

 <?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 a gunar solution (thanks to gunar!), But it adds some details that I found along the way. For example, I could not see the res directories that I did until I changed the Project view, and an integer resource type already exists, so we do not need to declare the columns as an element, and then set the integer type. (BTW: I love the Android XML tool!)

+2
source share

All Articles