Java – Fit a ImageView (and its src) to the layout width and make its height proportional

androidjavalayout

Can you help me to configure my layout? I don't achieve what I'm looking for:

I've put the imageview background to red for explain what I want:

The image's width is smaller than the layout width. I'd like the image grow proportionally keeping its aspect ratio until reach the aspect at the first image (I modified it manually with photoshop) but when setting width="fill_parent" the result is the second image and setting both width and height to "fill_parent" the result is the third image.

I tried to combine with ScaleType with no success

How can I achieve the first option? Thanks

enter image description here

Best Answer

Use android:adjustViewBounds=true attr in xml for ImageView


This question is solved here by extending the ImageView class.

Android ImageView adjusting parent's height and fitting width


I created a sample. It works for me. Here is the xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView android:src="@drawable/hydrangeas"
        android:layout_height="wrap_content" android:id="@+id/imageView1"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        android:background="@android:color/white"
        android:layout_width="wrap_content"/>

</LinearLayout>

It works for fitCenter too. Have a look at the snapshot.
With centerInside and adjustViewBounds="true"