首页 文章

Android imageview不尊重maxWidth?

提问于
浏览
107

所以,我有一个imageview应该显示一个任意图像,一个从互联网上下载的 Profiles 图片 . 我希望ImageView能够缩放其图像以适应父容器的高度,并设置最大宽度为60dip . 但是,如果图像比例较高,并且不需要完整的60dip宽度,则ImageView的宽度应该减小,以便视图的背景紧贴图像 .

我试过这个,

<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"/>

但由于某些原因,这使得ImageView超大,也许它使用了图像的固有宽度和wrap_content来设置它 - 无论如何,它不尊重我的maxWidth属性 . 这只适用于某些类型的容器吗?它在LinearLayout中......

有什么建议?

2 回答

  • 2

    啊,

    android:adjustViewBounds="true"
    

    是maxWidth工作所必需的 .

    现在就行!

  • 285

    如果您使用 match_parent ,则设置 adjustViewBounds 无效,但解决方法很简单 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);
        }
    }
    

相关问题