ImageView adjustViewBounds not working with Relative Layout

浪尽此生 提交于 2020-01-01 09:23:12

问题


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>

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>

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)?


回答1:


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

I got it there




回答2:


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);
}


来源:https://stackoverflow.com/questions/28035724/imageview-adjustviewbounds-not-working-with-relative-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!