Android imageview not respecting maxWidth?

前端 未结 2 969
暗喜
暗喜 2020-12-02 09:26

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 th

相关标签:
2条回答
  • 2020-12-02 09:56

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 10:16

    Ah,

    android:adjustViewBounds="true"
    

    is required for maxWidth to work.

    Works now!

    0 讨论(0)
提交回复
热议问题