### 緒
很多朋友都沉迷于自定義View, 而自定義View離不開measure、layout、draw三個步驟,在測量方面,很多朋友僅僅是知道怎么去測量一個控件,而對于為什么要這么做等等問題都搞的不是很清楚,今天這篇文章我們就從View樹的最頂層`DecorView`開始分析測量到底是怎么一回事。
這篇文章要解決的問題有:
> 1. onMeasure的兩個參數從哪來。
> 1. 最開始的參數是怎么計算出來的。
> 1. 測量規格是根據什么得到的。
### 一切從DecorView說起
大家都知道在我們的應用窗口中最頂層的View是`DecorView`, 那么自然而然,一個測量的開始肯定就是從DecorView開始的,而且,我們還知道,一個測量的開始是從`ViewRootImpl`的`performTraversals`方法開始,所以我們理所當然的要從`performTraversals`方法開始看起。`performTraversals`很長,看起來甚至有點可怕,不過沒關系,我們僅僅關心我們需要的代碼就ok,
~~~
private void performTraversals() {
...
if (!mStopped) {
boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
(relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
|| mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
// mark
// 獲取測量規格 mWidth和mHeight當前視圖frame的大小
// lp是WindowManager.LayoutParams
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
+ mWidth + " measuredWidth=" + host.getMeasuredWidth()
+ " mHeight=" + mHeight
+ " measuredHeight=" + host.getMeasuredHeight()
+ " coveredInsetsChanged=" + contentInsetsChanged);
// Ask host how big it wants to be
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
...
}
...
}
}
~~~
在這里我們看到了performMeasure,那這里肯定就是測量的開始了,但是,重點是我們關心的`childWidthMeasureSpec`和`childWidthMeasureSpec`是怎么計算出來的, 這里調用了`getRootMeasureSpec`方法,我們來到這個方法一探究竟。
~~~
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;
}
~~~
這個方法很簡單,就是根據`rootDimension`的值來定義不同的`measureSpec`
> 當是MATCH_PARENT的時候,我們make一個大小是windowSize,規格是精確值的MeasureSpec
當是WRAP_CONTENT的時候,我們make一個大小是windowSize,規格是最大為windowSize的MeasureSpec
其他的情況,也就是rootDimension是具體值,那我們得到的是一個大小為rootDimension,規格為精確的MeasureSpec
### DecorView的測量
通過看上面的代碼,我們最終有了一個測量規格,而且,我們可以猜測到寬高值都是固定的,就是我們視圖的大小,所以,最后的measureSpec是精確的。現在我們就來到DecorView,看看到底是怎么測量的。
~~~
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 獲取測量規格, 這里是EXACTLY
final int widthMode = getMode(widthMeasureSpec);
final int heightMode = getMode(heightMeasureSpec);
boolean fixedWidth = false;
// 這里有點意思,如果不是EXACTLY的
// 這里還是要獲取下視圖的大小
// 讓測量規格是EXACTLY
if (widthMode == AT_MOST) {
final TypedValue tvw = isPortrait ? mFixedWidthMinor : mFixedWidthMajor;
if (tvw != null && tvw.type != TypedValue.TYPE_NULL) {
final int w;
if (tvw.type == TypedValue.TYPE_DIMENSION) {
w = (int) tvw.getDimension(metrics);
} else if (tvw.type == TypedValue.TYPE_FRACTION) {
w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels);
} else {
w = 0;
}
if (w > 0) {
// 這里重新設置了測量規格
// 大小是performMeasure中給出的大小和自己獲取的大小的最小值
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(
Math.min(w, widthSize), EXACTLY);
fixedWidth = true;
}
}
}
...
// 下面同樣有一個高度的判斷
...
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
~~~
DecorView的測量有點意思,在發現`performMeasure`中給的測量規格不是精確值的時候,自己又去獲取一下并且取兩者的最小值,當然這里肯定是吧測量規格設置為精確值了。判斷好后,接著調用了super.onMeasure,通過源碼我們可以知道其實DecorView繼承自FrameLayout,所以,現在我們要去FrameLayout的onMeasure方法看看了。
### FrameLayout的測量
~~~
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
// 如果測量規格有一個不是精確值,這里就為true
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
// 測量子view
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
// 寬度為前一個計算出來的寬度和當前view的寬度取最大值
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
// 如果當前view有match_parent的地方,
// 記錄一下當前view
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// 一些常規的邊邊角角和保證現在的大小能包含的了所有組件
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
// 保存測量結果
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
// 這里有值表明了兩點:
// 1 當前FrameLayout的寬和高的建議規格有不是精確值的
// 2 子view有含有match_parent的地方
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
getPaddingLeftWithForeground() - getPaddingRightWithForeground() -
lp.leftMargin - lp.rightMargin,
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() -
getPaddingTopWithForeground() - getPaddingBottomWithForeground() -
lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
~~~
FrameLayout的測量很簡單,先去計算所有子view中最大的寬和高,然后調用resolveSizeAndState去最終確認大小, 那我們來看看resolveSizeAndState方法到底干了嘛,這個方法位于View類中,
~~~
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
if (specSize < size) {
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result | (childMeasuredState&MEASURED_STATE_MASK);
}
~~~
這里的邏輯也很簡單,但是絕對是有代表性的,我們自己寫的測量跟這里有很大的相似之處,首先這里去判斷測量規格,如果是EXACTLY,則結果直接是MeasureSpec里獲取的大小,如果是AT_MOST,這里取兩個大小的最小值。到這里FrameLayout的測量也就完成了,而且我們也看懂了測量是如何從DecorView開始一步步的到child的測量過程,不過這個過程我們還沒有細看。
### 測量子view
下面我們就從measureChildWithMargins方法開始分析一下如何進行的子view的測量,這個方法在ViewGroup中定義的。
~~~
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
~~~
代碼我們也都似曾相識,關鍵點還是在`getChildMeasureSpec`中,這里獲取了父Group對子View的建議,最后調用child.measure將建議傳遞進去,從而開始了整個View樹的測量流程。
~~~
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
int size = Math.max(0, specSize - padding);
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on u
// 如果父view的規格是精確值
case MeasureSpec.EXACTLY:
// 如果子view的layout_XXX是一個確定的值
if (childDimension >= 0) {
// 測建議的值是子view指定的值
// 規格是EXACTLY
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// 如果子view的layout_XXX是MATCH_PARENT
// 則建議的值是子view自己想要的的大小,也就是父view剩下的大小
// 規格是EXACTLY
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// 如果子view的layout_XXX是WRAP_CONTENT
// 則建議的值是子view自己想要的的大小,也就是父view剩下的大小
// 規格是AT_MOST
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
// 如果父view的規格是AT_MOST
case MeasureSpec.AT_MOST:
// 如果子view的layout_XXX是一個確定的值
if (childDimension >= 0) {
// 測建議的值是子view指定的值
// 規格是EXACTLY
// Child wants a specific size... so be it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// 如果子view的layout_XXX是MATCH_PARENT
// 則建議的值是子view自己想要的的大小,也就是父view剩下的大小
// 規格是AT_MOST
// Child wants to be our size, but our size is not fixed.
// Constrain child to not be bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// 如果子view的layout_XXX是WRAP_CONTENT
// 則建議的值是子view自己想要的的大小,也就是父view剩下的大小
// 規格是AT_MOST
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent asked to see how big we want to be
// 如果父view的規格是不確定的
case MeasureSpec.UNSPECIFIED:
// 如果子view的layout_XXX是一個確定的值
if (childDimension >= 0) {
// 測建議的值是子view指定的值
// 規格是EXACTLY
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// 如果子view的layout_XXX是MATCH_PARENT
// 則建議的值0
// 規格是UNSPECIFIED
// Child wants to be our size... find out how big it should
// be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// 如果子view的layout_XXX是WRAP_CONTENT
// 則建議的值0
// 規格是UNSPECIFIED
// Child wants to determine its own size.... find out how
// big it should be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
~~~
這里的代碼正是measureSpec依據什么而來最有力的回答,在代碼中已經注釋的很詳細了,不過下面還是要總結一下:
> 1. 父View是EXACTLY,子view的大小指定為確定值,則給子view的建議大小是子view自己設置的大小,規格為EXACTLY。
> 1. 父View是EXACTLY,子view的大小指定為MATCH_PARENT,則給子view的建議大小是父view剩下的大小,規格為EXACTLY。
> 1. 父View是EXACTLY,子view的大小指定為WRAP_CONTENT,則給子view的建議大小是父view剩下的大小,規格為AT_MOST。
> 1. 父View是AT_MOST,子view的大小指定為確定值,則給子view的建議大小是子view自己設置的大小,規格為EXACTLY。
> 1. 父View是AT_MOST,子view的大小指定為MATCH_PARENT,則給子view的建議大小是父view剩下的大小,規格為AT_MOST。
> 1. 父View是AT_MOST,子view的大小指定為WRAP_CONTENT,則給子view的建議大小是父view剩下的大小,規格為AT_MOST。
> 1. 父View是UNSPECIFIED,子view的大小指定為確定值,則給子view的建議大小是子view自己設置的大小,規格為EXACTLY。
> 1. 父View是UNSPECIFIED,子view的大小指定為MATCH_PARENT,則給子view的建議大小0,規格為UNSPECIFIED。
> 1. 父View是UNSPECIFIED,子view的大小指定為WRAP_CONTENT,則給子view的建議大小0,規格為UNSPECIFIED。
### 最后的最后
ok, 到這里,我們雖然只是分析了DecorView和他的父類FrameLayout的測量流程,不過這也算是將整個流程分析完了,為什么這么說呢? 只要我們看到了measure child的部分,就是走完了一個閉環,接下來的子view的測量流程和上面的一樣,只不過是測量的細節不一樣罷了,最后,我們再來看一個方法,很多同學寫測量的時候都會使用`getDefaultSize`這個方法,那么這個方法究竟干了什么呢?
~~~
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
~~~
是不是又一種似曾相識的感覺,這里的邏輯也很簡單,就是根據測量規格是定義不用的大小,如果是UNSPECIFIED,則結果就是我們傳遞進來的size,如果是AT_MOST或者EXACTLY,則結果就是我們父布局建議的大小。很多同學可能喜歡這么用,
~~~
int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
~~~
這樣做有一個坑,在一些viewgroup中獲得的結果是0,為什么呢? 例如HorizontalScrollView,從源碼上看, 它最后給子view建議的規格會是UNSPECIFIED,從`getDefaultSize`源碼上看,此時結果就是我們傳遞的size,也就是`getSuggestedMinimumWidth`返回的值,我們來看看這個方法的定義,
~~~
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
~~~
這里取值是我們設置的minWidth和背景的minWidth的最大值,如果minWidth和背景我們都沒有設置的話,這里返回的也是0了,這樣,我們就能理解結果為什么是0了。 從這個小問題是還能看出一點,我們在自己寫測量的時候不能只依靠父布局,而是要參考父布局的建議和自己的測量結果。任何有**霸權**傾向的測量都是不可取的。
好了,這篇文章就到這里吧,相信大家在仔細閱讀后會對View的測量機制有一個全新的認識。