这是对 Nestor Perez 上述解决方案的补充,但我将专注于 onMeasure() 的 Kotlin 代码,用于解析高度和宽度。
首先我们声明 width 和 height 变量并将它们设置为 0。
class CustomRectangle @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
//width and height variables
private var widthSize = 0
private var heightSize = 0
//PAINT OBJECT
private val paint = Paint().apply {
style = Paint.Style.FILL
}
......}
在度量内部,我们使用 resolveSizeAndState() 方法来计算 2 个维度。然后我们如下图设置高度和宽度。
//ON_MEASURE
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val minWidth: Int = paddingLeft + paddingRight + suggestedMinimumWidth
val w: Int = resolveSizeAndState(minWidth, widthMeasureSpec, 1)
val h: Int = resolveSizeAndState(MeasureSpec.getSize(w), heightMeasureSpec, 0)
widthSize = w
heightSize = h
setMeasuredDimension(w, h)
}
然后onDraw() 我们使用解析后的 height 和 width 绘制自定义矩形。
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.color = Color.Whatever_Color
canvas.drawRect(0f, 0f, widthSize.toFloat(), heightSize.toFloat(), paint)
}
然后正如 Nestor Perez 上面解释的那样,我们将宽度和高度设置为 0dp。
<com.custombutton
android:id="@+id/custom_button"
android:layout_width="0dp"
android:layout_height="0dp" ..../>
干杯