一、measure過程
1、View的measure過程
View的measure方法是一個(gè)final方法,不可重寫,在measure中會(huì)去調(diào)用自身的onMeasure方法。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
/**
* Utility to return a default size. Uses the supplied size if the
* MeasureSpec imposed no constraints. Will get larger if allowed
* by the MeasureSpec.
*
* @param size Default size for this view
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
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;
}
setMeasuredDimension方法會(huì)設(shè)置View寬高的測(cè)量值。
在getDefaultSize方法中,在AT_MOST與EXACTLY情況下,都返回measureSpec的尺寸,即測(cè)量后的尺寸。
UNSPECIFIED一般用于系統(tǒng)內(nèi)部的測(cè)量過程,返回getSuggestedMinimumWidth作為尺寸
#View.java
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
#Drawable.java
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
從源碼看出,在getSuggestedMinimumWidth方法中,如果View沒有設(shè)置背景,則返回mMinWidth,否則返回minWidth與mBackground的寬度的最大值。minWidth默認(rèn)為0。
getSuggestedMinimumWidth總結(jié):
(1)如果View沒有設(shè)置背景,則返回minWidth,這個(gè)可以為0
(2)如果View設(shè)置了背景,則返回背景寬度與minWidth的最大值。
注意
直接繼承View的自定義控件需要重寫onMeasure方法并設(shè)置wrap_content時(shí)的自身大小,否則在布局中使用wrap_content就相當(dāng)于使用match_parent。
原因:當(dāng)View使用wrap_content時(shí),它的specMode是AT_MOST模式,specSize為parentSize,即父布局當(dāng)前剩余的空間大小,同時(shí)在AT_MOST模式下,onMeasure會(huì)直接返回specSize值。
2、ViewGroup的measure過程
對(duì)于ViewGroup來說,除了完成自己的measure過程外,還會(huì)遍歷調(diào)用所有子元素的measure方法,各個(gè)子元素再遞歸執(zhí)行這個(gè)過程。ViewGroup并沒有重寫onMeasure方法,但它提供了一個(gè)measureChildren的方法。之所以沒有重寫onMeasure方法,我個(gè)人的想法是因?yàn)樗淖宇惗及裲nMeasure方法都重寫了,所以它寫沒啥意義。
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);
}
}
}
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的思想他就是取出子元素的LayoutParams,然后再通過getChildMeasureSpec來創(chuàng)建子元素的MeasureSpec,接著將MeasureSpc直接傳遞給View的measure方法進(jìn)行測(cè)量。
不同的ViewGroup子類有不同的measure實(shí)現(xiàn)方式,以下針對(duì)LinearLayout分析。
3、LinearLayout measure過程
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//TODO 省略部分代碼
// See how tall everyone is. Also remember max width.
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
if (child == null) {
mTotalLength += measureNullChild(i);
continue;
}
if (child.getVisibility() == View.GONE) {
i += getChildrenSkipCount(child, i);
continue;
}
...
if (heightMode == MeasureSpec.EXACTLY && useExcessSpace) {
...
} else {
...
// Determine how big this child would like to be. If this or
// previous children have given a weight, then we allow it to
// use all available space (and we will shrink things later
// if needed).
//TODO 步驟1
final int usedHeight = totalWeight == 0 ? mTotalLength : 0;
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
final int childHeight = child.getMeasuredHeight();
if (useExcessSpace) {
// Restore the original height and record how much space
// we've allocated to excess-only children so that we can
// match the behavior of EXACTLY measurement.
lp.height = 0;
consumedExcessSpace += childHeight;
}
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
if (useLargestChild) {
largestChildHeight = Math.max(childHeight, largestChildHeight);
}
}
...
//TODO 步驟2
// 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);
...
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
if (matchWidth) {
forceUniformWidth(count, heightMeasureSpec);
}
}
(1)LinearLayout會(huì)遍歷子元素并對(duì)每個(gè)子元素執(zhí)行measureChildBeforeLayout方法,這個(gè)方法實(shí)際上執(zhí)行的是ViewGroup.measureChildWithMargins方法,且LinearLayout通過mTotalLength來存儲(chǔ)LinearLayout在豎直方向的初步高度。增加的部分主要包括子元素的高度以及子元素在豎直方向上的margin等。
(2)當(dāng)子元素測(cè)量完畢后,LinearLayout會(huì)根據(jù)子元素的情況測(cè)量自己的大小,在豎直方向上,如果它的布局中高度采用的是match_parent或者具體數(shù)值,那么它的測(cè)量過程和View一致,高度為specSize;如果它的布局高度采用wrap_content,那么它的高度是所有子元素所占高度的總和,但仍然不超過它的父容器的剩余空間。
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
final int specMode = MeasureSpec.getMode(measureSpec);
final int specSize = MeasureSpec.getSize(measureSpec);
final int result;
switch (specMode) {
case MeasureSpec.AT_MOST:
if (specSize < size) {
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}
3、獲取View的measuredWidth/measuredHeight時(shí)機(jī)
(1)Activity/View#onWindowFocusChanged
這個(gè)方法的含義是:View已經(jīng)初始化完畢了,寬高已經(jīng)準(zhǔn)備好了。當(dāng)Activity的窗口得到或失去焦點(diǎn)時(shí)均會(huì)被調(diào)用一次。
(2)view.post()
通過post將一個(gè)runnable投遞到消息隊(duì)列的尾部,等待Looper調(diào)用此runnable。
(3)ViewTreeObserver
ViewTreeObserver里有眾多回調(diào)可以完成這個(gè)功能。
(4)view.measure()
通過手動(dòng)對(duì)View進(jìn)行measure來得到View的寬高。
二、layout過程
layout的作用是ViewGroup用來確定子元素的位置,當(dāng)ViewGroup的位置被確定后,它在onLayout中會(huì)遍歷所有的子元素并調(diào)用其layout方法。
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
onLayout(changed, l, t, r, b);
if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}
mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLayoutChangeListeners != null) {
ArrayList<OnLayoutChangeListener> listenersCopy =
(ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
int numListeners = listenersCopy.size();
for (int i = 0; i < numListeners; ++i) {
listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
}
}
}
final boolean wasLayoutValid = isLayoutValid();
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
...
}
通過setFrame方法設(shè)定View的四個(gè)頂點(diǎn)位置,即初始化mLeft,mRight,mTop,mBottom,View的四個(gè)頂點(diǎn)一旦確定,那么View在容器中的位置也就確定;接著會(huì)調(diào)用onLayout方法,用于確定子元素的位置。
不同的View的onLayout規(guī)則不一樣,以下以LinearLayout舉例:
1、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);
}
}
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
// Where right end of child should go
final int width = right - left;
int childRight = width - mPaddingRight;
// Space available for child
int childSpace = width - paddingLeft - mPaddingRight;
final int count = getVirtualChildCount();
...
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
int gravity = lp.gravity;
if (gravity < 0) {
gravity = minorGravity;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / 2)
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = paddingLeft + lp.leftMargin;
break;
}
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
childTop += lp.topMargin;
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
layoutVertical方法中,會(huì)遍歷所有子元素并調(diào)用setChildFrame來為子元素指定對(duì)應(yīng)的位置,其中childTop會(huì)逐漸增大,這就意味著后面的子元素被放置在靠下的位置。
2、getMeasuredWidth與getWidth區(qū)別
public final int getWidth() {
return mRight - mLeft;
}
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
在View的默認(rèn)實(shí)現(xiàn)中,View的測(cè)量寬高和最終寬高是相等的,只不過測(cè)量寬高形成于View的measure過程,最終寬高形成于View的layout過程,賦值時(shí)機(jī)不同。可以認(rèn)為View的測(cè)量寬高與最終寬高相等。
三、draw過程
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* 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
int saveCount;
drawBackground(canvas);
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
drawAutofilledHighlight(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
if (debugDraw()) {
debugDrawFocus(canvas);
}
// we're done...
return;
}
...
}
View的繪制過程遵循如下幾步:
(1)繪制背景background.draw(canvas)
(2)繪制自己(onDraw)
(3)繪制children(dispatchDraw)
(4)繪制裝飾(onDrawScrollBars)
View的繪制過程的傳遞是通過dispatchDraw來實(shí)現(xiàn)的,dispatchDraw會(huì)遍歷調(diào)用所有元素的draw方法,如此draw事件就一層層的傳遞了下去。
View#setWillNotDraw
/**
* If this view doesn't do any drawing on its own, set this flag to
* allow further optimizations. By default, this flag is not set on
* View, but could be set on some View subclasses such as ViewGroup.
*
* Typically, if you override {@link #onDraw(android.graphics.Canvas)}
* you should clear this flag.
*
* @param willNotDraw whether or not this View draw on its own
*/
public void setWillNotDraw(boolean willNotDraw) {
setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
}
如果一個(gè)View不需要繪制任何內(nèi)容,那么設(shè)置這個(gè)標(biāo)記為true以后,系統(tǒng)會(huì)進(jìn)行相應(yīng)的優(yōu)化。默認(rèn)情況下View沒有啟用這個(gè)優(yōu)化標(biāo)記位,但是ViewGroup會(huì)默認(rèn)啟用這個(gè)標(biāo)記位。
這個(gè)標(biāo)記位對(duì)實(shí)際開發(fā)的意義是:當(dāng)我們的自定義控件繼承于ViewGroup并且本身不具備繪制功能時(shí),就可以開啟這個(gè)標(biāo)記位從而便于系統(tǒng)進(jìn)行后續(xù)的優(yōu)化。
結(jié)尾
摘抄自《Andorid開發(fā)藝術(shù)探索》