Manpreet
Manpreet

Reputation: 580

Drawable Image does not scale as per screen density

I have an ImageView that is a part of ListItemView that is suppose to be displayed in the ListView. Without the Image, each item of listview takes less height. This is consistent across all the screens as they all are of same height. However, in one of the activities, I need to display an image in the listview items and this always increases the size of each item for that activity. I have the proper folder structure under res > drawable > family > family (hdpi), family (mdpi), family (xhdpi), family (xxhdpi), fmaily (xxxhdpi)

So each image has 5 version based upon the screen density.

I have the below in my layout file:

<ImageView
        android:id="@+id/image"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right|center"/>

and I am setting the image in Java code:

ImageView imageView = listItemView.findViewById(R.id.image);
imageView.setImageResource(word.getImage());

However, no matter what resolution I choose, the image size always seems to be the same and it affects the size of the whole ListItemView in the ListView.

Size of ListView item without image:

Without ImageView

With ImageView:

enter image description here

You may have noticed the change in the height of the ListView item with gray background. Is this normal. I dont want to fix the size of the image. I would like to scale it based upon screen resolution, however, it should not distort the overall height of the ListView item. This image remains the same no matter what the screen density is. why won't it scale automatically and fit the ListView item.

Is this normal or is there any workaround for this?

Upvotes: 0

Views: 620

Answers (1)

Barns
Barns

Reputation: 4848

You are allowing the Image to decide how much space it can use by setting android:layout_height="wrap_content" and then having the width scale accordingly (in order for your layout_weight to work properly).

You could change your layout to force the ImageView to the height you prefer and let the use the scaleTypeto get the preferred scaling. In this example I used fitCenter but there are others that can be chosen (eg. fitXY).

By using the size qualifier dp the image will automatically "scale" with screen density as dp is Density-independent Pixels which means it will change with the screen density.

<ImageView
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:scaleType="fitCenter"
        android:layout_weight="1"
        android:layout_gravity="right|center"/>

Upvotes: 1

Related Questions