@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
解決的方法總結(jié):
- 1专缠。指定一個默認的內(nèi)部寬高,例如本方法中的desiredWidth = 100。
- 2。判斷當MeasureSpec的模式為AT_MOST(對應(yīng)于wrap_content)時损肛,設(shè)置結(jié)果為設(shè)置的值(最大為我們設(shè)置的值,如果小于設(shè)置值就設(shè)置為specSize)荣瑟。
- 3治拿。判斷當MeasureSpec的模式為非AT_MOST時,直接設(shè)置為系統(tǒng)的測量值即可笆焰。
- 4劫谅。設(shè)置值沒有特定的標準,以實際情況為準嚷掠。