Android – setting size of grid view items according to screensize

While working in an android project, I came across a situation where the grid item’s size was differing with screensize.

This is my gridview

<GridView
android:id=”@+id/PhoneImageGrid”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:columnWidth=”90dp”
android:gravity=”center”
android:horizontalSpacing=”10dp”
android:numColumns=”auto_fit”
android:stretchMode=”columnWidth”
android:verticalSpacing=”10dp” />

 

Obvious because, in my gridview’s adapter, I had set the dimensions as 150 * 150 px.

 imageView.setLayoutParams(new GridView.LayoutParams(150,150)); //dimension in px

where imageView is my gridview.

This worked perfect for Samsung Galaxy S-II phone, but looked smaller in S-III

The trick here is to set the dimensions in dp in dimens.xml , so  the android system calculates the dimension according to screensize while displaying the grid item.

In values/dimens.xml , set the width and height

Eg: 

<dimen name=”width”>100dp</dimen>
<dimen name=”height”>100dp</dimen>

In the adapter’s get view, get the dimensions from Resources and set it as follows

imageView.setLayoutParams(new GridView.LayoutParams(
(int)mContext.getResources().getDimension(R.dimen.width),
(int)mContext.getResources().getDimension(R.dimen.height)));

Thats it. This works good across different phone sizes.

Advertisements

3 thoughts on “Android – setting size of grid view items according to screensize

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s