Marcellino247 Marcellino247 - 27 days ago 13
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="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_view_bambini14"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="@integer/grid_columns" <!-- grid_colums value is set in res/values, in case the display is landscape or portrait-->
android:horizontalSpacing="10sp"
android:verticalSpacing="10sp"
android:gravity="center"
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.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT , 260));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
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?
Thanks!

Answer

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>
Comments