Marcellino247 Marcellino247 - 1 year ago 98
Android Question

Android gridview row height according to the display

and sorry for my english.
A simple question (if you know the answer :-D):
I have a GridView with only images, all the images are same size. I have set the numbers of colums in xml. Here is the code:

<GridView xmlns:android=""
android:numColumns="@integer/grid_columns" <!-- grid_colums value is set in res/values, in case the display is landscape or portrait-->
android:stretchMode="columnWidth" >

And this is the java code:

Public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT , 260));
} else {
imageView = (ImageView) convertView;
return imageView;

the problem is the row height. In some smartphone the images are show in the right way, in other (I suppose according to resolution and density of the monitor) the row are too high.
I tried to change this row

imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT , 260));

with different values instead of 260, ando so to put GridView.AUTO_FIT, but the result is always obscene.
How can I fix it?

Answer Source

One possible problem of why the height appears differently on various devices is the way you specify the height here:

imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 260));

A good starting point to your problem would be using density pixels instead:

imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, context.getResources().getDimension(R.dimen.grid_view_item_height)));

And specify grid_view_item_height in resources:

<dimen name="grid_view_item_height">100dp</dimen>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download