緒
很多朋友都沉迷於自定義View, 而自定義View離不開measure、layout、draw三個步驟,在測量方面,很多朋友僅僅是知道怎麼去測量一個控件,而對於爲什麼要這麼做等等問題都搞的不是很清楚,今天這篇文章我們就從View樹的最頂層DecorView
開始分析測量到底是怎麼一回事。
這篇文章要解決的問題有:
- onMeasure的兩個參數從哪來。
- 最開始的參數是怎麼計算出來的。
- 測量規格是根據什麼得到的。
一切從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依據什麼而來最有力的回答,在代碼中已經註釋的很詳細了,不過下面還是要總結一下:
- 父View是EXACTLY,子view的大小指定爲確定值,則給子view的建議大小是子view自己設置的大小,規格爲EXACTLY。
- 父View是EXACTLY,子view的大小指定爲MATCH_PARENT,則給子view的建議大小是父view剩下的大小,規格爲EXACTLY。
- 父View是EXACTLY,子view的大小指定爲WRAP_CONTENT,則給子view的建議大小是父view剩下的大小,規格爲AT_MOST。
- 父View是AT_MOST,子view的大小指定爲確定值,則給子view的建議大小是子view自己設置的大小,規格爲EXACTLY。
- 父View是AT_MOST,子view的大小指定爲MATCH_PARENT,則給子view的建議大小是父view剩下的大小,規格爲AT_MOST。
- 父View是AT_MOST,子view的大小指定爲WRAP_CONTENT,則給子view的建議大小是父view剩下的大小,規格爲AT_MOST。
- 父View是UNSPECIFIED,子view的大小指定爲確定值,則給子view的建議大小是子view自己設置的大小,規格爲EXACTLY。
- 父View是UNSPECIFIED,子view的大小指定爲MATCH_PARENT,則給子view的建議大小0,規格爲UNSPECIFIED。
- 父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的測量機制有一個全新的認識。