Android imageview not respecting maxWidth?
Asked Answered
P

2

123

So, I have an imageview that should display an arbitrary image, a profile picture downloaded from the internet. I want this the ImageView to scale its image to fit inside the height of the parent container, and a set max width of 60dip. However, if the image is tall ratio-wise, and doesn't need the full 60dip of width, the ImageView's width should decrease so the view's background fits snugly around the image.

I tried this,

<ImageView android:id="@+id/menu_profile_picture"
    android:layout_width="wrap_content"
    android:maxWidth="60dip"
    android:layout_height="fill_parent"
    android:layout_marginLeft="2dip"
    android:padding="4dip"
    android:scaleType="centerInside"
    android:background="@drawable/menubar_button"
    android:layout_centerVertical="true"/>

but that made the ImageView super large for some reason, maybe it used the intrinsic width of the image and wrap_content to set it - anyway, it didn't respect my maxWidth attribute.. Does that only work inside some types of containers? It's in a LinearLayout...

Any suggestions?

Prismoid answered 20/8, 2010 at 11:15 Comment(0)
P
330

Ah,

android:adjustViewBounds="true"

is required for maxWidth to work.

Works now!

Prismoid answered 20/8, 2010 at 11:23 Comment(3)
and programmatically: imageView.setAdjustViewBounds(true);Banket
For anyone coming across this finding it doesn't work, make sure the width/height are not set to match_parent.Risotto
And here I've been stealing AOSP's special internal ImageView that was supposedly created to respect these bounds.Mellicent
P
4

Setting adjustViewBounds does not help if you use match_parent, but workaround is simple custom ImageView:


public class LimitedWidthImageView extends ImageView {
    public LimitedWidthImageView(Context context) {
        super(context);
    }

    public LimitedWidthImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LimitedWidthImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int specWidth = MeasureSpec.getSize(widthMeasureSpec);
        int maxWidth = getMaxWidth();
        if (specWidth > maxWidth) {
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth,
                    MeasureSpec.getMode(widthMeasureSpec));
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
Phosphine answered 16/7, 2015 at 18:29 Comment(1)
adjustViewBounds seems to work fine with a match_parent width for me.Gomel

© 2022 - 2024 — McMap. All rights reserved.