內容:View的三大工作流程源碼分析
measure過程
1.View的measure過程
- 由measure方法來完成,該方法是靜態的不能被子類重寫,在view的measure中會調用onMeasure:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension方法設置寬高的測量值,看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;
}
EXACTLY情況:getDefaultSize返回的大小就是MeasureSpec中的specSize,這個specSize就是測量后的大小。
UNSPECIFIED情況:view的大小為size,即寬高分別為getSuggestedMinimumWidth和getSuggestedMinimumHeight的返回值
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
可以看出,如果view沒有設置背景,那么view的寬度為mMinWidth,mMinWidth 對應于android:minWidth屬性所指的值,
不指定默認為0。如果view指定背景,則view的寬度為max(mMinWidth, mBackground.getMinimumWidth()),看下getMinimumWidth()方法
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
getMinimumWidth()返回的就是Drawable的原始寬度,沒有原始寬度則為0,例:ShapeDrawable無原始寬度,BitmapDrawable有。
- 總結:從getDefaultSize方法中來看,View的寬高由specSize決定。
結論:直接繼承View的自定義控件需要重寫onMeasure方法并設置wrap_content時的自身大小,否則wrap_content效果為match_parent。
原因:結合上述代碼和表4-1理解,上述代碼中可知view在代碼中使用wrap_content,那么specMode是AT_MOST模式,寬高等于
specSize;差表4-1可知,這種情況specSize是parentSize,而parentSize是父容器中可以使用的大小,match_parent效果一致。
解決:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if ((widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth,mHeight);
}else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpaceSize, mHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mWidth, heightSpaceSize);
} else {
}
}
在代碼中只需要給view指定一個默認的內部寬高(mWidth,mHeight),并在wrap_content時設置即可,對于非wrap_content沿用系統的測量值即可。(可參考TextView,imageView源碼)
2.ViewGroup的measure過程
- 對于ViewGroup除了完成自己的measure過程外,還會調用所有子元素的measure方法,各個子元素再遞歸去執行這個過程。ViewGroup是一個抽象類,沒有重寫view的onMeasure方法,但提供了measureChildren方法:
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);
}
}
}
ViewGroup在measure時,會對每一個子元素進行measure,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思想是取出子元素的LayoutParams,然后再通過getChildMeasureSpec來創建子元素的MeasureSpec,接著將MeasureSpec直接傳遞給View的measure方法來進行測量。
- 下面通過LinearLayout的onMeasure方法來分析ViewGroup的measure過程。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
看下measureVertical方法:由于有300行代碼所以只看核心
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,heightMeasureSpec, usedHeight);
final int childHeight = child.getMeasuredHeight();
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
}
}
系統會遍歷子元素并對每個子元素執行measureChildBeforeLayout方法,這個方法內部會調用measure方法,各個元素依次進入measure過程,系統會通過mTotalLength來存儲LinearLayout在豎直方向的初步高度。每測量一個子元素mTotalLength都會增加,增加的部分主要包括了子元素的高度以及子元素在豎直方向上的margin等.當子元素測量完畢后,LinearLayout測量自己的大小:
// 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;
···
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
對豎直LinearLayout而言,它在水平方向的測量過程遵循View的測量過程,在豎直方向的測量過程則和view不同。如果它的布局中高度采用的是mathch_parent或者具體數值,那么它的測量過程與view一致,即高度為specSize;如果它的布局中高度采用wrap_content,那么它的高度是所有子元素所占的高度總和,但是仍然不能超過父容器的剩余空間,它的最終高度還需要考慮其在豎直方向的padding,看源碼:
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);
}
measure完成后,通過getMeasureWidth/Heigth獲取測量高度。在極端情況下系統多次measure才能確定最終高度,這種情況在onMeasure方法中拿到的測量寬高不準確。好的習慣是在onLayout方法中獲得View的測量寬高或最終寬高。
- 一種情況:在Activity已啟動的時候就做一件任務,任務需要獲取某個View的寬高。
View的measure過程和Activity的生命周期方法不是同步執行,無法保證Activity執行了onCreate、onStart、onResume時View已經測量完畢,如果View還沒有測量完畢,那么獲得的寬高就是0。
四種解決辦法:
(1)Activity/View#onWindowFocusChanged
onWindowFocusChanged方法含義:View已經初始化完畢,寬高已經準備好了,這時候獲取寬高沒有問題。注意:當Activty繼續執行和暫停執行時,onWindowFocusChanged均會被調用,如果頻繁的進行onResume和onPause,那么onWindowFocusChanged也會被頻繁的調用。代碼:
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
}
(2)view.post(runnable)
通過post可以將一個runnable投遞到消息隊列尾部,然后等待Looper調用此runnable的時候,View也已經初始化好了,代碼:
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override
public void run() {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
(3)VeiwTreeObserver
使用VeiwTreeObserver的眾多回調可以完成這個功能,比如使用
OnGlobalLayoutListener接口,當View樹的狀態發生改變或者View樹內部的View的可見性發生改變時,onGlobalLayout方法將被回調,此時獲取View的寬高。注意:伴隨view樹的狀態改變,onGlobalLayout會被調用多次。
protected void onStart() {
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
(4)view.measure(int widthMeasureSpec, int heightMeasureSpec)
手動對View進行measure來得到View的寬高。根據View的LayoutParams分情況處理:
- match_parent
無法measure出具體寬高。 - 具體的數值(dp/px)
比如寬高都是100px:
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
- wrap_content
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
注意:(1 << 30) - 1通過分析MeasureSpec的實現可以知道,View的尺寸使用30位二進制表示,最大是30個1(即2^30-1),也就是(1 << 30) - 1,在最大化模式下,我們用View理論上能支持的最大值去構造MeasureSpec是合理的。
- 關于View的measure的錯誤用法:原因是違背系統內部實現規范導致measure過程出錯,從而結果不能保證是正確的,錯誤代碼:
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec( - 1, MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(-1, MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout過程
作用是ViewGroup用來確定子元素的位置,確定后它在onLayout中遍歷所有子元素并調用其layout方法,在layout方法中onLayout方法又被調用。
- layout方法確定View本身的位置,onLayout確定所有子元素的位置,view的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);
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);
}
}
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
首先通過setFrame方法設定view的四個頂點的位置,即初始化 mLeft、mTop、mBottom、mRight四值,確定view在父容器中的位置;接著調用onLayout方法,這個方法的用途是父容器確定子元素的位置,實現與具體布局有關,所以View和ViewGroup沒有真正實現onLayout方法。
- 看下LinearLayout的onLayout方法:
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);
}
}
layoutVertical部分代碼:
void layoutVertical(int left, int top, int right, int bottom) {
···
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();
···
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);
}
}
}
setChildFrame中的Width和Height實際上就是子元素的測量寬高,
此方法會遍歷所有子元素并調用setChildFrame方法為子元素指定對應位置,childTop會逐漸增大,子元素放在靠下位置。
setChildFrame調用子元素的layout方法,父元素在layout方法中完成自己的定位后,通過onLayout方法調用子元素的layout方法,子元素又會通過自己的layout方法來確定自己的位置,這樣一層層傳遞下去就完成了整個View樹的layout過程。
setChildFrame方法:
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
在layout方法中會通過setFrame去設置子元素的四個頂點的位置,在setFrame中有幾句賦值語句,這樣子元素的位置就確定了
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
- 問題:View的測量寬高與最終寬高的區別?
問題具體為:View的getMeasuredWidth和getWidth這兩種方法有什么區別。
首先看getWidth和getHeight的方法實現:
public final int getWidth() {
return mRight - mLeft;
}
public final int getHeight() {
return mBottom - mTop;
}
getWidth方法返回的是View的測量寬度。
答案:在View的默認實現中,View的測量寬高和最終寬高是相等的,區別在于測量寬高形成于View的measure過程,而最終寬高形成于View的layout過程,測量寬高的賦值時機稍微早一些。
在日常開發中可以認為View的測量寬高等于最終寬高,特殊情況下才會不同。
draw過程
View的繪制過程遵循如下幾步:
- 繪制背景background.draw(canvas).
- 繪制自己(onDraw).
- 繪制children(dispatchaDraw).
- 繪制裝飾(onDrawScrollBars)
源碼:
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
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;
if (!dirtyOpaque) {
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
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(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);
// we're done...
return;
}
···
}
View繪制過程的傳遞是通過dispatchDraw來實現,dispatchDraw會遍歷調用所有子元素的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中不需要繪制任何內容,那么設置這個標記位為true以后,系統會進行相應的優化。
默認情況下view沒有啟動這個默認標記位,但是ViewGroup會默認啟動這個優化標記位。
實際開發的意義:當我們的自定義控件繼承ViewGroup并且本身不具備繪制功能時,就可以開啟這個標記位便于系統進行后續的優化。當明確知道一個ViewGroup需要通過onDraw來繪制內容時,我們需要顯示的關閉WILL_NOT_DRAW這個標記位。