一、measure過程
1、View的measure過程
View的measure方法是一個final方法,不可重寫宴霸,在measure中會去調(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方法會設(shè)置View寬高的測量值。
在getDefaultSize方法中瓢谢,在AT_MOST與EXACTLY情況下畸写,都返回measureSpec的尺寸,即測量后的尺寸氓扛。
UNSPECIFIED一般用于系統(tǒng)內(nèi)部的測量過程枯芬,返回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默認為0淫痰。
getSuggestedMinimumWidth總結(jié):
(1)如果View沒有設(shè)置背景,則返回minWidth整份,這個可以為0
(2)如果View設(shè)置了背景待错,則返回背景寬度與minWidth的最大值。
注意
直接繼承View的自定義控件需要重寫onMeasure方法并設(shè)置wrap_content時的自身大小烈评,否則在布局中使用wrap_content就相當于使用match_parent火俄。
原因:當View使用wrap_content時,它的specMode是AT_MOST模式讲冠,specSize為parentSize瓜客,即父布局當前剩余的空間大小,同時在AT_MOST模式下竿开,onMeasure會直接返回specSize值忆家。
2、ViewGroup的measure過程
對于ViewGroup來說德迹,除了完成自己的measure過程外,還會遍歷調(diào)用所有子元素的measure方法揭芍,各個子元素再遞歸執(zhí)行這個過程胳搞。ViewGroup并沒有重寫onMeasure方法,但它提供了一個measureChildren的方法称杨。之所以沒有重寫onMeasure方法肌毅,我個人的想法是因為它的子類都把onMeasure方法都重寫了,所以它寫沒啥意義姑原。
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方法進行測量锭汛。
不同的ViewGroup子類有不同的measure實現(xiàn)方式笨奠,以下針對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會遍歷子元素并對每個子元素執(zhí)行measureChildBeforeLayout方法般婆,這個方法實際上執(zhí)行的是ViewGroup.measureChildWithMargins方法到腥,且LinearLayout通過mTotalLength來存儲LinearLayout在豎直方向的初步高度。增加的部分主要包括子元素的高度以及子元素在豎直方向上的margin等蔚袍。
(2)當子元素測量完畢后乡范,LinearLayout會根據(jù)子元素的情況測量自己的大小,在豎直方向上啤咽,如果它的布局中高度采用的是match_parent或者具體數(shù)值晋辆,那么它的測量過程和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時機
(1)Activity/View#onWindowFocusChanged
這個方法的含義是:View已經(jīng)初始化完畢了,寬高已經(jīng)準備好了盼玄。當Activity的窗口得到或失去焦點時均會被調(diào)用一次贴彼。
(2)view.post()
通過post將一個runnable投遞到消息隊列的尾部,等待Looper調(diào)用此runnable埃儿。
(3)ViewTreeObserver
ViewTreeObserver里有眾多回調(diào)可以完成這個功能器仗。
(4)view.measure()
通過手動對View進行measure來得到View的寬高。
二童番、layout過程
layout的作用是ViewGroup用來確定子元素的位置精钮,當ViewGroup的位置被確定后,它在onLayout中會遍歷所有的子元素并調(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的四個頂點位置轨香,即初始化mLeft,mRight幼东,mTop臂容,mBottom,View的四個頂點一旦確定根蟹,那么View在容器中的位置也就確定脓杉;接著會調(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方法中散庶,會遍歷所有子元素并調(diào)用setChildFrame來為子元素指定對應(yīng)的位置蕉堰,其中childTop會逐漸增大凌净,這就意味著后面的子元素被放置在靠下的位置。
2嘁灯、getMeasuredWidth與getWidth區(qū)別
public final int getWidth() {
return mRight - mLeft;
}
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
在View的默認實現(xiàn)中泻蚊,View的測量寬高和最終寬高是相等的,只不過測量寬高形成于View的measure過程丑婿,最終寬高形成于View的layout過程性雄,賦值時機不同「睿可以認為View的測量寬高與最終寬高相等秒旋。
三、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來實現(xiàn)的诀拭,dispatchDraw會遍歷調(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);
}
如果一個View不需要繪制任何內(nèi)容耕挨,那么設(shè)置這個標記為true以后细卧,系統(tǒng)會進行相應(yīng)的優(yōu)化。默認情況下View沒有啟用這個優(yōu)化標記位筒占,但是ViewGroup會默認啟用這個標記位贪庙。
這個標記位對實際開發(fā)的意義是:當我們的自定義控件繼承于ViewGroup并且本身不具備繪制功能時,就可以開啟這個標記位從而便于系統(tǒng)進行后續(xù)的優(yōu)化翰苫。
結(jié)尾
摘抄自《Andorid開發(fā)藝術(shù)探索》