I have an ImageView which I want to always be the same size. If the image is smaller than the view, I’d like it to be centred in the view. If the Image is larger than the view then I’d like it scaled down – with aspect ratio preserved.
I’ve had several attempts at this myself – the latest of which is:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/itemImage" android:layout_width="100dp"
android:layout_height="100dp" android:scaleType="fitCenter"
android:adjustViewBounds="true" android:gravity="center" android:padding="10px" />
<TextView android:id="@+id/currentLentItem" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:padding="10px"/>
</LinearLayout>
What am I missing here?
Try using the scale type
centerInside, like below:This causes the image to scale down only if larger than the layout, and it will scale proportionally as well (whereas fitXY scales without regard to aspect ratio). It will also center the image if smaller.
EDIT: I’ve updated the example for something like you’re wanting. Here’s the gist of what changed:
• ImageView gravity changed to
right|center_vertical. Since you want them to align on the right, using this gravity will allow that even if they are portrait orientation images.• ImageView aligned to the right of the RelativeLayout
• RelativeLayout set to
wrap_contentsince it’s to be used for a ListView.• TextView added, aligned to the parent’s left, with its right edge defined by the left edge of itemImage.