Search code examples
androidandroid-layoutandroid-imageviewlistviewitemandroid-relativelayout

Content Inset with Custom Drawable Scaling


I have a ListView with custom items defined in a relativeLayout, which includes an imageView with android:layout_width="match_parent" and android:layout_height="wrap_content" and a custom vector drawable as a source, which schematically looks like this:

+-------------------------------------------+
+    solid area              | some picture +
+-------------------------------------------+

The issue is when I turn to the landscape mode the image gets scaled up (to mach the parent's width), however keeping the aspect ratio the height is increased, as well.

Ideally I would like to define a Content Inset (as I know it from iOS), so that the solid area above gets stretched to match the new width, and the 'some picture'-area is kept at the same aspect ratio. All in all I the scaling would happen such that the height of the image (and hence of the whole listView item) is kept the same.


Solution

  • You can get the solid area to stretch by using a LinearLayout with a layout weight in the child width. To make this work, you should assign a fixed width to the ImageView.

    Also, the adjustViewBounds attribute on the ImageView will help to maintain the correct aspect ratio.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:orientation="horizontal">
    
        <!-- this can be any view or view group, the layout params are the important part-->
        <View
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            ...
            />
    
        <!-- set this to an absolute width that will be the same for portrait & landscape -->
        <ImageView
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            ...
            />
    
    </LinearLayout>