測量分兩步:
第一步,獲取測量模式和尺寸
// 獲取測量模式和尺寸
val mode = MeasureSpec.getMode(widthMeasureSpec)
val size = MeasureSpec.getSize(widthMeasureSpec)
第二步瑟蜈,根據(jù)測量模式分別測量尺寸
// 根據(jù)不同測量模式分別測量
when (mode) {
MeasureSpec.EXACTLY -> {
result = size
}
MeasureSpec.AT_MOST -> {
result = 200
result = Math.min(result, size)
}
MeasureSpec.UNSPECIFIED -> {
result = 200
}
}
測量模式:
完整代碼:
package com.gorhaf.lab
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val TAG = "CustomView"
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(
measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec)
)
}
private fun measureWidth(widthMeasureSpec: Int): Int {
// 默認大小
var result = 0
// 獲取測量模式和尺寸
val mode = MeasureSpec.getMode(widthMeasureSpec)
val size = MeasureSpec.getSize(widthMeasureSpec)
// 根據(jù)不同測量模式分別測量
when (mode) {
MeasureSpec.EXACTLY -> {
result = size
}
MeasureSpec.AT_MOST -> {
result = 200
result = Math.min(result, size)
}
MeasureSpec.UNSPECIFIED -> {
result = 200
}
}
return result
}
private fun measureHeight(heightMeasureSpec: Int): Int {
// 默認大小
var result = 0
// 獲取測量模式和尺寸
val mode = MeasureSpec.getMode(heightMeasureSpec)
val size = MeasureSpec.getSize(heightMeasureSpec)
// 根據(jù)不同測量模式來測量
when (mode) {
MeasureSpec.EXACTLY -> {
result = size
}
MeasureSpec.AT_MOST -> {
result = 200
result = Math.min(result, size)
}
MeasureSpec.UNSPECIFIED -> {
result = 200
}
}
// 返回大小
return result
}
}