Android 图像视图不尊重 maxWidth?

所以,我有一个图像视图,应该显示一个任意的图像,一个配置文件图片从互联网上下载。我希望这个 ImageView 缩放其图像,以适应内的高度父容器,并设置最大宽度为60下降。然而,如果图像是高比例的,并且不需要完整的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"/>

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...

有什么建议吗?

34608 次浏览

啊,

android:adjustViewBounds="true"

是 maxWidth 工作所必需的。

起作用了!

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