首页 > 解决方案 > Android ImageView - 当adjustViewBounds=true时minWidth/minHeight没有效果

问题描述

我正在尝试使用 adjustViewBounds 包装较大的图像,但是虽然这是真的 minWidth/minHeight 不会保留用于较小的图像,并且它会占用图像的实际大小。

标签: androidandroid-layoutandroid-imageview

解决方案


如果您查看ImageView中“onMeasure()”方法的源代码,您会发现最小宽度和最小高度在使用或时都不起作用。如果也为真,则这些调整大小变量设置为真。resizeWidth == trueresizeHeight == trueadjustViewBounds

您可以介绍自定义ImageViewminWidth的使用和minHeight何时使用,如下所示:adjustViewBounds == true

class MyImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatImageView(context, attrs) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            max(suggestedMinimumWidth, measuredWidth),
            max(suggestedMinimumHeight, measuredHeight)
        )
    }
}

推荐阅读