代码之家  ›  专栏  ›  技术社区  ›  juell

Android imageview不尊重maxWidth?

  •  107
  • juell  · 技术社区  · 14 年前

    所以,我有一个imageview,它可以显示一个任意的图片,一个从互联网下载的个人资料图片。我希望ImageView将其图像缩放到适合父容器的高度,并将最大宽度设置为60dip。但是,如果图像是高比例的,并且不需要完全倾斜60度的宽度,那么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\u内容来设置它-无论如何,它不尊重我的maxWidth属性。。这只适用于某些类型的容器吗?它呈直线布局。。。

    有什么建议吗?

    2 回复  |  直到 14 年前
        1
  •  312
  •   juell    14 年前

    啊,

    android:adjustViewBounds="true"
    

    是maxWidth工作所必需的。

    现在工作!

        2
  •  4
  •   FeelGood    9 年前

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