onMeasure函数如下:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
onMeasure函数的调用者:
包含这个View的具体的ViewGroup调用,参数也就是从这个ViewGroup中传入的。
widthMeasureSpec与heightMeasureSpec来源与作用:
来源:
由ViewGroup中的layout_width,layout_height、padding、layout_margin和weight共同决定。
作用:
这两个值由高32位和低16位组成。高32位保存的值叫specMode,低16位的值叫specSize。分别可以通过getMode()和getSize()获取。
specMode类型:
- MeasureSpec.EXACTLY:LayoutParams.MATCH_PARENT。
- MeasureSpec.AT_MOST:LayoutParams.WRAP_CONTENT。
- MeasureSpec.UNSPECIFIED:我们可以随意指定视图的大小。
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}