文章目錄
-
-
- View的測量、布局和繪制過程中父View(目前View)和子View的先後順序
-
- onMeasure過程
-
- LinearLayout#onMeasure
- LinearLayout#measureChildBeforeLayout
- LinearLayout#measureChildWithMargins方法:
- ViewGroup#getChildMeasureSpec方法
- View#measure
- onLayout過程
-
- View#layout
- View#setFrame
- LinearLayout#onLayout源碼:
- LinearLayout#setChildFrame
- onDraw過程
-
- ViewGroup#dispatchDraw
- 總結
- 參考
-
View的測量、布局和繪制過程中父View(目前View)和子View的先後順序
View的測量、布局和繪制過程中,到底是先測量(布局、繪制)父View,還是先測量子View,這篇文章會從源碼角度給出答案。
onMeasure過程
View的測量是從measure方法開始的,我們就先看下View#measure的方法:
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
if (forceLayout || needsLayout) {
...
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
} else {
...
}
...
}
...
}
可以看出,measure會調用View#onMeasure方法進行測量。
再來看下View#onMeasure的實作:其實就是設定測量寬高。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
LinearLayout#onMeasure
我們知道,ViewGroup一般會重寫View#onMeasure方法,不同的ViewGroup的實作方式大同小異,我們以LinearLayout為例:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
我們這裡選擇垂直方向的measureVertical方法:
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
mTotalLength = 0;
...
// 循環周遊所有child,調用View#measure進行測量
// See how tall everyone is. Also remember max width.
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
...
if (heightMode == MeasureSpec.EXACTLY && useExcessSpace) {
...
} else {
...
// 測量child的寬高
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
// child測量完成後,擷取測量後的高度
final int childHeight = child.getMeasuredHeight();
...
// 将child的高度累加到mTotalLength中
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
}
...
}
...
// Add in our padding
mTotalLength += mPaddingTop + mPaddingBottom;
// 将mTotalLength指派給heightSize,并對heightSize進行轉化
int heightSize = mTotalLength;
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// 将heightSize和heightMeasureSpec轉化為heightSizeAndState
// Reconcile our calculated size with the heightMeasureSpec
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
...
// 調用View#setMeasuredDimension方法設定LinearLayout的的測量寬高
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
...
}
①這裡開啟一個for循環,會先去測量每個子View的大小。
②子View測量完畢後,會将測量寬高分别指派給每個View的
mMeasuredWidth
和
mMeasuredHeight
。
③接着會将每個子View的高度值累加給成員變量
mTotalLength
④接着将
mTotalLength
轉換後指派給
heightSize
,再将
heightSize
轉換後指派給
heightSizeAndState
。
⑤在
measureVertical
方法最後調用
setMeasuredDimension
方法,利用得到的
heightSizeAndState
去設定LinearLayout的高度。
簡而言之,就是先調用子view的measure進行測量,完成後将其寬高記錄下來,等所有子View測量完成後,就可以得到目前View的寬高了。
是以測量過程是先測量子View,再測量父View,因為父View的寬高會用到子View的測量結果。
LinearLayout#measureChildBeforeLayout
我們這裡簡單看下LinearLayout#measureChildBeforeLayout方法:它調用了measureChildWithMargins
void measureChildBeforeLayout(View child, int childIndex,
int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
int totalHeight) {
measureChildWithMargins(child, widthMeasureSpec, totalWidth,
heightMeasureSpec, totalHeight);
}
LinearLayout#measureChildWithMargins方法:
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);
}
該方法分為三步:
①擷取child的MarginLayoutParams參數。
②通過ViewGroup#getChildMeasureSpec方法分别生成寬度和高度的MeasureSpec。
③利用生成的MeasureSpec參數,調用View#measure方法對子View進行測量。
我們仔細看下getChildMeasureSpec方法的參數,會發現第二個參數是目前View的padding值和child的margin的值,也就是說子View的測量大小受限于父View的padding和子View的margin。
ViewGroup#getChildMeasureSpec方法
接着我們來看下ViewGroup測量的核心:ViewGroup#getChildMeasureSpec方法。
我們常說的
子View的測量由父View和子View共同影響
,就是來源于這個方法。
// spec是父View的MeasureSpec參數;
// padding的值由父View的padding值和子View的margin值相加而來;
// childDimension是子View的MeasureSpec參數;
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 us
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// 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
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// 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) {
// 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
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size... find out how big it should
// be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
如下圖所示:該圖表中的内容其實是對getChildMeasureSpec方法的總結。
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcukTNzIjNx0SMwcDM5EDMyg1VvwVbvNmLkV3bsNWc51mLn5WaqlWZi1Cch5ycvNmLygDN4gjN1UjMx0yZu9Gdn52b0lnbpR3Lc9CX6MHc0RHaiojIsJye.png)
View#measure
前面說過,繪制完子View後,子View的測量寬高
mMeasuredWidth
和
mMeasuredHeight
會被指派,接下來我們看下這個過程的源碼。
View#measure -->
View#onMeasure -->
View#setMeasuredDimension -->
View#setMeasuredDimensionRaw
我們看下View#setMeasuredDimensionRaw源碼:
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
可以很明顯的看出,View的
mMeasuredWidth
和
mMeasuredHeight
會被指派,這樣在View測量完成後,我們就可以通過
View#getMeasuredWidth
和
View#getMeasuredHeight
方法擷取到View的測量寬高了。
onLayout過程
布局的過程從View#layout方法開始.
View#layout
public void layout(int l, int t, int r, int b) {
...
// 對目前View進行布局
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
// 調用onLayout方法。
onLayout(changed, l, t, r, b);
...
}
...
}
這裡根據isLayoutModeOptical的值會分别調用setOpticalFrame和setFrame方法,翻看源碼可知,setOpticalFrame方法也是調用setFrame方法的,是以不論isLayoutModeOptical的值為true還是false,都會調用View#setFrame方法對目前View進行布局。
接下來會調用View#onLayout方法,通過該方法我們可以确定子View的位置。
通過檢視源碼可知,View和ViewGroup的onLayout方法都是空實作,而且ViewGroup#onLayout方法還被定義為了抽象方法,強制子類必須實作。
View#onLayout:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
ViewGroup#onLayout:
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
View#setFrame
protected boolean setFrame(int left, int top, int right, int bottom) {
boolean changed = false;
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
...
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
...
}
return changed;
}
可以看出,通過setFrame方法來設定View的四個頂點的位置,它們的值一旦确定,那麼View在父容器中的位置也就确定了。
關于View#onLayout方法的實作,這裡我們還是以LinearLayout為例進行說明。
LinearLayout#onLayout源碼:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} else {
layoutHorizontal(l, t, r, b);
}
}
我們選擇LinearLayout#layoutVertical進行分析:
void layoutVertical(int left, int top, int right, int bottom) {
...
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
...
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
...
}
}
}
可以看出,這裡循環周遊所有子View,并調用LinearLayout#setChildFrame方法對子View進行布局定位。
LinearLayout#setChildFrame
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
它的實作很簡單,就是調用View#layout方法進行定位。
綜上所述,View布局的核心方法是View#layout方法,先對父View(目前View)進行布局,然後調用onLayout方法對子View進行布局定位。
onDraw過程
View的繪制過程也是從View#draw(Canvas canvas)方法開始的,
public void draw(Canvas canvas) {
...
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
// Step 1, draw the background, if needed
if (!dirtyOpaque) {
drawBackground(canvas);
}
...
// Step 2, save the canvas' layers
...
saveCount = canvas.getSaveCount();
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
...
canvas.restoreToCount(saveCount);
drawAutofilledHighlight(canvas);
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
}
如上可知,繪制流程按照以下六個步驟執行:
①繪制背景
②如果需要,儲存圖層
③繪制目前View的内容
④繪制子View,具體是dispatchDraw方法
⑤如果需要,繪制邊界,恢複圖層
⑥繪制相關裝飾(比如滾動條)
不出意外,dispatchDraw方法在View中是空實作,如下所示:
protected void dispatchDraw(Canvas canvas) {
}
ViewGroup#dispatchDraw
我們看下dispatchDraw的具體實作,是在ViewGroup當中:
@Override
protected void dispatchDraw(Canvas canvas) {
...
for (int i = 0; i < childrenCount; i++) {
...
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
more |= drawChild(canvas, child, drawingTime);
}
}
...
}
這裡也是循環周遊每個子View,然後調用ViewGroup#drawChild方法對每個子View進行繪制。
我們看下ViewGroup#drawChild的實作:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
實作很簡單,就是調用View#draw方法對每個子View進行繪制。
總的來說,View繪制的核心方法是View#draw方法,先對父View(目前View)進行繪制,然後調用dispatchDraw方法對子View進行繪制。
總結
1、測量過程是先測量子View,再測量父View(目前View),因為父View的寬高需要用到子View的測量結果。
2、View布局的核心方法是View#layout方法,先對父View(目前View)進行布局,然後調用onLayout方法對子View進行布局定位。
3、View繪制的核心方法是View#draw方法,先對父View(目前View)進行繪制,然後調用dispatchDraw方法對子View進行繪制。
參考
1、圖解View測量、布局及繪制原理
2、View的測量、布局和繪制過程中的關鍵方法