- 对于自定义的控件如果要支持wrap_content属性就必须重写onMeasure()方法
- 重写onMeasure()方法其实就是为了给自定义的控件一个在AT_MOST模式下的默认大小。
kotlin模板代码如下:
//重写onMeasure方法,使得控件支持AT_MOST
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(
measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec)
)
}
private fun measureWidth(measureSpec: Int): Int {
var result = 0
val specMode = MeasureSpec.getMode(measureSpec)
val specSize = MeasureSpec.getSize(measureSpec)
if (specMode == MeasureSpec.EXACTLY) {
result = specSize
} else {
result = 375//宽度默认大小
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize)
}
}
return result
}
private fun measureHeight(measureSpec: Int): Int {
var result: Int
val specMode = MeasureSpec.getMode(measureSpec)
val specSize = MeasureSpec.getSize(measureSpec)
if (specMode == MeasureSpec.EXACTLY) {
result = specSize
} else {
result = 350//高度默认大小
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize)
}
}
return result
}
网友评论