前言
任何View要顯示在屏幕上,都需要經(jīng)過測量(measure)、布局(layout)、繪制(draw)三大流程,measure負(fù)責(zé)確定View的大小,layout負(fù)責(zé)確定View的位置,draw負(fù)責(zé)繪制View的內(nèi)容。這篇我們就先來通過源碼分析一下View的測量(measure)流程。源碼基于Android API 21。
測量由ViewRootImpl#performTraversals開始
在[由setContentView探究Activity加載流程]中,我們提到View三大工作流程是從ViewRootImpl#performTraversals方法開始的,其中performMeasure、performLayout、performDraw方法分別對應(yīng)了View的測量、布局、繪制。如下:
private void performTraversals() {
...
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
...
performLayout(lp, desiredWindowWidth, desiredWindowHeight);
...
performDraw();
}
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
可以看到,在performMeasure
方法中調(diào)用了 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)
,這里的mView其實是DecorView,它并沒有重寫measure
方法,因為View#measure方法被final修飾,不可被重寫。因此我們看下View#measure方法。
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
······
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
······
}
在View#measure中又調(diào)用了onMeasure(widthMeasureSpec, heightMeasureSpec)
方法。并且DecorView重寫了onMeasure
方法,在DecorView#onMeasure方法中主要是
進一步確定自己的widthMeasureSpec
、heightMeasureSpec
,并調(diào)用super.onMeasure(widthMeasureSpec, heightMeasureSpec)
即FrameLayout#onMeasure方法。
ViewGroup 的Measure過程
ViewGroup是一個抽象類,它并沒有重寫onMeasure方法,具體的實現(xiàn)交由子類去處理,如LinearLayout、RelativeLayout、FrameLayout,這是因為不同ViewGroup的布局特性和實現(xiàn)細(xì)節(jié)各異,無法統(tǒng)一處理。在這里我們以FrameLayout為例分析ViewGroup的測量過程。
FrameLayout#onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();//獲取子View的數(shù)量
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) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
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) {
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();
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);
}
}
}
View的Measure過程
先來看下View中的measure方法
/**
* <p>
* The actual measurement work of a view is performed in
* {@link #onMeasure(int, int)}, called by this method. Therefore, only
* {@link #onMeasure(int, int)} can and must be overridden by subclasses.
* </p>
*/
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
······
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
······
}
可以看到此方法是final的,不可以被重寫,并且注釋中也表明實際的測量工作是在onMeasure方法中進行的,所以我們直接看onMeasure方法即可。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasureDimension方法其實是用來存儲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;
}
這個方法是用來確定View最終測量大小的。由View自身的measureSpec(測量規(guī)則)獲取specMode(測量模式)和specSize(測量大小),當(dāng)specMode為AT_MOST、EXACTLY這兩種模式時,返回的大小就是此View的測量大小。當(dāng)specMode為UNSPECIFIED時,返回大小是getSuggestedMinimumWidth和getSuggestedMinimumHeight這兩個方法的返回值。
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
這兩個方法原理是一樣的,這里選擇getSuggestedMinimumWidth來分析。
首先判斷View有沒有設(shè)置背景,如果沒有,則返回mMinWidh,mMinWidth對應(yīng)于android:minWidth這個屬性對應(yīng)的值,如果沒有指定這個屬性值,則默認(rèn)為0。
如果設(shè)置了背景,則返回mMinWidth和 getMinimumWidth返回值之間的最大值。
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
在getMinimumWidth方法中,getIntrinsicWidth得到是背景的原始高度,如果背景原始高度大于0,則返回背景的原始高度,否則返回0。
至此getDefaultSize方法具體返回值就確定了,View最終的測量大小也就確定了。
注意:
當(dāng)自定義View時,如果直接繼承了View,在必要的時候需要重寫onMeasure方法并在其中對wrap_content的情況進行處理。這是為什么呢?
從getDefaultSize方法中可以看到,當(dāng)specMode為AT_MOST時,返回的大小為specSize,這個specSize其實是父View的大小,如果這里不明白,可以參考Android中View測量之MeasureSpec中普通View的MeasureSpec創(chuàng)建過程。
當(dāng)確定了View的最終測量大小后,會把測量的寬高作為參數(shù)傳入setMeasuredDimension方法。
/**
* <p>This method must be called by {@link #onMeasure(int, int)} to store the
* measured width and measured height. Failing to do so will trigger an
* exception at measurement time.</p>
*/
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
......
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
......
}
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
看注釋就可以明白,其實這個方法就是用來存儲測量的寬和高,并且如果沒有設(shè)置這個方法,測量時將會產(chǎn)生異常。
其內(nèi)部通過setMeasuredDimensionRaw方法會將View的最終測量寬高賦值給變量mMeasuredWidth,mMeasuredHeight進行存儲。
另外我們可以通過getMeasuredWidth,getMeasuredHeight方法得到mMeasuredWidth、mMeasuredHeight對應(yīng)的值,即View的最終的測量寬高。如下:
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
public final int getMeasuredHeight() {
return mMeasuredHeight & MEASURED_SIZE_MASK;
}
至此View的measure過程就分析完了,不過這里的View指的是像TextView、ImageView、Button這中不能含有子View的View,如果是一個ViewGroup類型的View,像LinearLayout、RelativeLayout、FrameLayout可以包含多個子View,那么它的measure過程又是怎樣的,我們接著分析ViewGroup的measure過程。
ViewGroup的Measure過程
ViewGroup是一個抽象類,它并沒有重寫onMeasure方法,具體的實現(xiàn)交由子類去處理,如LinearLayout、RelativeLayout、FrameLayout,這是因為不同ViewGroup的布局特性和實現(xiàn)細(xì)節(jié)各異,無法統(tǒng)一處理。對于ViewGroup,它不但要測量自身大小,還要去測量每個子View的大小,我們先來分析一下ViewGroup中measureChildren方法,看它是如何測量子View的,如下:
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
這個方法比較清晰,首先獲取子View的數(shù)量,然后遍歷子View,最后調(diào)用measureChild方法。
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
在measureChild方法中先獲取了子View的布局參數(shù),然后通過父View的MeasureSpec、和子View的布局參數(shù)經(jīng)過getChildMeasureSpec方法創(chuàng)建子View的MeasureSpec,這個方法已經(jīng)在Android中View測量之MeasureSpec中做了詳細(xì)介紹,當(dāng)確定了子View的MeasureSpec后,就可以測量子View的大小了,接著調(diào)用子View的measure方法。至此,測量過程就從父View傳遞到了子View了。如果子View也是個ViewGroup將會重復(fù)ViewGroup的Measure過程,如果子View是單個View,將執(zhí)行View的Measure過程,如此反復(fù),就完成了整個View樹的測量。
那ViewGroup具體是怎么確定自身最終測量大小的呢,下面我們以LiearLayout為例,來分析一下其onMeasure方法。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
我們以豎直方向為例,來看下measureVertical方法的主要內(nèi)容。
...
for (int i = 0; i < count; ++i) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
...
measureChildBeforeLayout(
child, i, widthMeasureSpec, 0, heightMeasureSpec,
totalWeight == 0 ? mTotalLength : 0);
...
final int childHeight = child.getMeasuredHeight();
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +lp.bottomMargin + getNextLocationOffset(child));
...
final int margin = lp.leftMargin + lp.rightMargin;
final int measuredWidth = child.getMeasuredWidth() + margin;
maxWidth = Math.max(maxWidth, measuredWidth);
...
}
...
// Add in our padding
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
// Check against our minimum height
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// Reconcile our calculated size with the heightMeasureSpec
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
...
maxWidth += mPaddingLeft + mPaddingRight;
// Check against our minimum width
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
上述代碼做了如下工作:
- 遍歷LinearLayout中的所有子View,并調(diào)用measureChildBeforeLayout方法,這個方法內(nèi)部會調(diào)用measureChildWithMargins(這個方法和上文提到的measureChild方法原理一樣,只不過在創(chuàng)建子View的MeasureSpec的時候考慮了子View的margin)方法,接著在measureChildWithMargins內(nèi)部會執(zhí)行子View的measure方法來測量子View的大小。
- 當(dāng)子View測量完畢后,就可以通過getMeasuredWidth方法獲取子View的測量寬度,并且用變量maxWidth來存儲所有子View中(狀態(tài)為View.Gone的除外)child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + mPaddingLeft + mPaddingRight 中的最大值;
通過getMeasuredHeight方法獲取子View的測量高度,并用變量mTotalLength來存儲所有子View(狀態(tài)為View.Gone的除外)的childHeight + lp.topMargin +lp.bottomMargin + getNextLocationOffset(child) + mPaddingTop + mPaddingBottom之和; - 最后執(zhí)行resolveSizeAndState方法最終確定自身測量大小。
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);
}
- 水平方向上,如果LinearLayout的寬度為match_parent 或具體的數(shù)值(MeasureSpec.EXACTLY),則LinearLayout的寬度就為自身測量規(guī)則確定的大小,如果LinearLayout的寬度為wrap_parent(MeasureSpec.AT_MOST),則LinearLayout的高度就為所有子View中占用水平空間最大的那個View所占空間大小加上LinearLayout自身的水平方向上的padding,但是大小仍然不會超過父View的寬度。
- 在豎直方向上,如果LinearLayout的高度為match_parent 或具體的數(shù)值(MeasureSpec.EXACTLY),則LinearLayout的高度就為自身測量規(guī)則確定的大小,如果LinearLayout的高度為wrap_parent(MeasureSpec.AT_MOST),則LinearLayout的高度就為所有子View占用的空間大小加上LinearLayout自身的豎直方向上的padding,但是大小仍然不會超過父View的高度。
以上就是ViewGroup的measure過程。
至此,measure篇就講完了,真心希望對各位猿寶寶在measure過程的理解上有所幫助!!!
若文中有錯誤或表述不當(dāng)?shù)牡胤竭€望指出,多多交流,共同進步。