Autosize Images in Android

Problem
Images were displaying in a way that was not desired, by default. Many times we want images to display with the same width and height while maintaining the aspect ratio of the image. Typically we also want to be able to see our images have consistent widths and heights, especially when working with tiles or lists.

Solution
I paste the basic layout of one of my adapters to illustrate.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/row_parent"
    android:orientation="horizontal"
    android:padding="10dp"
    android:weightSum="4">

    <FrameLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitCenter"
            android:id="@+id/img_profile"
            android:adjustViewBounds="true"/>
    </FrameLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:id="@+id/container_profile_summary">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lbl_name" />

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lbl_occupation" />
    </LinearLayout>

</LinearLayout>
android:scaleType="fitCenter"

This will apply ScaleType.FIT_CENTER which as the documentation states

Scale the image using CENTER.

CENTER as the documentation states will

Compute a scale that will maintain the original src aspect ratio, but will also ensure that src fits entirely inside dst. At least one axis (X or Y) will fit exactly. The result is centered inside dst.

android:adjustViewBounds="true"

This attribute is important and required. Android says about this attribute

Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

I had issues making the ImageView work when I’m applying the scaling and using weights, so I put it as a child of a FrameLayout and found it to work successfully.

References