11

I have an ImageView and have set its layout_height to "100dp" and its layout_width to "wrap_content".

The drawable used has bigger actual dimensions that are 130dp (width) X 215dp (height).

When the ImageView is placed inside a LinearLayout, if I set adjustViewBounds to true, it gets a width that is measured according to the drawable's aspect ratio and the layout_width.

However, when placed inside a RelativeLayout the ImageView gets the same width as the drawable (130dp), no matter the adjustViewBounds settings.

In both cases the image renders correclty without distortion, however the ImageView's bounds are different.

The RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:adjustViewBounds="true"
        android:src="@drawable/phone_orange"
        android:contentDescription="@null" />

 </RelativeLayout>

ImageView in Relative Layout

The LinearLayout:

<?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="match_parent"
    android:background="@android:color/background_light"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:src="@drawable/phone_orange" />

</LinearLayout>

ImageView in LinearLayout

Why does the ImageView measures differently in these 2 scenarios? Is there a way to make the ImageView behave always like being in the LinearLayout case (wrapping it with a LinearLayout works but it's not a clean solution)?

Onik
  • 19,396
  • 14
  • 68
  • 91
Petrakeas
  • 1,521
  • 15
  • 28

2 Answers2

16
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:adjustViewBounds="true"

I got it there

Community
  • 1
  • 1
Kirill Shalnov
  • 2,216
  • 1
  • 19
  • 21
1

use width and height of imageview to match_parent

private void addView(Drawable d) {
    RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,     RelativeLayout.LayoutParams.MATCH_PARENT);
    ImageView iv = new ImageView(this);
    iv.setImageDrawable(d);
    iv.setAdjustViewBounds(true);
    iv.setScaleType(ImageView.ScaleType.MATRIX);
    iv.setLayoutParams(lparams);
    rl.addView(iv);
    iv.setOnTouchListener(this);
}