自定義View過(guò)程.png
用戶主動(dòng)調(diào)用 request,只會(huì)出發(fā) measure 和 layout 過(guò)程,而不會(huì)執(zhí)行 draw 過(guò)程
Paste_Image.png
onMeasure.png
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int viewWidth = circleRadius + this.getPaddingLeft() + this.getPaddingRight();
int viewHeight = circleRadius + this.getPaddingTop() + this.getPaddingBottom();
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(viewWidth, widthSize);
} else {
//Be whatever you want
width = viewWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(viewHeight, heightSize);
} else {
//Be whatever you want
height = viewHeight;
}
setMeasuredDimension(width, height);
}
measure的核心方法
- measure(int widthMeasureSpec,int heightMeasureSpec):是view中final方法,不能重寫(xiě),但是最終都會(huì)曲調(diào)用onMeasure方法
- onMeasure(int widthMeasureSpec,int heightMeasureSpec):發(fā)方法中兩個(gè)參數(shù)是父控件對(duì)子view的測(cè)量要求,在該方法中需要結(jié)合測(cè)量模式和測(cè)量大小以及邊界距離值確定view的最終大小
- setMeasureDimension(int width,int height):在onMeasure中得到最終的大小之后,一定要調(diào)用這個(gè)方法進(jìn)行最終的確定,否則會(huì)報(bào)錯(cuò)。
mCustomView.setPadding(0, top, 0, 0);等方法最終也會(huì)去調(diào)用requestLayout,調(diào)整padding的值,其中參數(shù)負(fù)數(shù)則代表反方向。