View 體系詳解:View 的工作流程
當我們呼叫startActivity()
方法的時候,會呼叫到ActivityThread
中的performLaunchActivity()
獲取一個 Activity 例項, 並在Instrumentation
的callActivityOnCreate()
方法中呼叫 Activity 的onCreate()
完成 DecorView 的建立。這樣我們就獲取了一個 Activity 的例項,然後我們呼叫handleResumeActivity()
來回調 Activity 的onResume()
:
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) { // .... WindowManagerGlobal.initialize(); // 建立 Activity 的例項,在這裡完成對 Activity 的 onCreate() 方法的回撥 Activity a = performLaunchActivity(r, customIntent); if (a != null) { // ... // 在這裡回撥 Activity 的 onResume() 方法 handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason); if (!r.activity.mFinished && r.startsNotResumed) { // 在這裡完成對 Activity 的 onPause() 方法的回撥 performPauseActivityIfNeeded(r, reason); // ... } } // ... } 複製程式碼
然後,在handleResumeActivity()
方法中的performResumeActivity()
會回撥 Activity 的onResume()
方法。在該方法中,我們會從 Window 中獲取之前新增進去的 DecorView,然後將其新增到 WindowManager 中:
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) { // 在這裡會回撥 Activity 的 onResume() r = performResumeActivity(token, clearHide, reason); if (r != null) { final Activity a = r.activity; // ... if (r.window == null && !a.mFinished && willBeVisible) { r.window = r.activity.getWindow(); // 在這裡獲取 DecorView View decor = r.window.getDecorView(); decor.setVisibility(View.INVISIBLE); // 獲取 WindowManager 例項,實際是 WindowManagerImpl ViewManager wm = a.getWindowManager(); WindowManager.LayoutParams l = r.window.getAttributes(); a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; if (r.mPreserveWindow) { a.mWindowAdded = true; r.mPreserveWindow = false; // Activity 被重建,複用 DecorView,通知子元素 ViewRootImpl impl = decor.getViewRootImpl(); if (impl != null) { impl.notifyChildRebuilt(); } } if (a.mVisibleFromClient) { if (!a.mWindowAdded) { a.mWindowAdded = true; // 將 DecorView 新增到 WindowManager 中 wm.addView(decor, l); } else { a.onWindowAttributesChanged(l); } } } } } 複製程式碼
這裡的WindowManager
是WindowManagerImpl
的例項,而呼叫它的addView()
方法的時候會使用WindowManagerGlobal
的addView()
方法。在該方法中會 new 出來一個ViewRootImpl
,然後呼叫它的setView()
把傳進來的DecorView
新增到Window
裡。同時,會呼叫requestLayout()
方法進行佈局,然後,並最終呼叫performTraversals()
完成對整個 View 樹進行遍歷:
private void performTraversals() { // ... if (!mStopped || mReportNextDraw) { // ... performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); } // ... final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw); boolean triggerGlobalLayoutListener = didLayout || mAttachInfo.mRecomputeGlobalAttributes; if (didLayout) { performLayout(lp, mWidth, mHeight); // ... } // ... if (!cancelDraw && !newSurface) { // ... performDraw(); } } 複製程式碼
在該方法中會呼叫performMeasure()
、performLayout()
和performDraw()
三個方法,它們分別會呼叫 DecorView 的measure()
、layout()
和draw()
完成對整個 View 樹的測量、佈局和繪製
,一個介面也就呈現給使用者了。如果您做過自定義 View 的話,那麼您對onMeasure()
、onLayout()
和onDraw()
三個方法一定不會陌生,前面的三個方法與後面的三個方法之間的關係就是:後面的三個方法會被前面的三個方法呼叫,本質上就是提供給使用者用來自定義的方法。下面我們就看下這三個方法究竟各自做了什麼操作,當然,我們儘可能從自定義控制元件的角度來分析,因為這對一個開發者可能幫助更大。
2、measure()
View 的大小不僅由自身所決定,同時也會受到父控制元件的影響,為了我們的控制元件能更好的適應各種情況,一般會自己進行測量。在上面我們提到了measure()
方法,它是用來測量 View 的大小的,但實際上測量的主要工作是交給onMeasure()
方法的。在 View 中,onMeasure()
是一個protected
的方法,顯然它設計的目的就是:提供給子 View 按照父容器提供的限制條件,控制自身的大小,實現自己大小的測量邏輯。所以,當我們自定義一個控制元件的時候,只會去覆寫onMeasure()
而不去覆寫measure()
方法。
在 Android 中,我們的控制元件分成 View 和 ViewGroup 兩種型別。根據上面的分析,對 View 的測量,我們可以得出如下結論:在 Android 中,ViewGroup 會根據其自身的佈局特點,把限制條件封裝成widthMeasureSpec
和heightMeasureSpec
兩個引數傳遞給子元素;然後,在子元素中根據這兩個引數來調整自身的大小。所以,ViewGroup 的measure()
方法會根據其佈局特性的不同而不同;而 View 的measure()
,不論其父容器是哪種型別,只根據widthMeasureSpec
和heightMeasureSpec
決定。
下面我們來看一下onMeasure()
在 View 和 ViewGroup 中的不同表現形式。
2.1 View 的 onMeasure()
下面是 View 類中的onMeasure()
方法。這是一個預設的實現,呼叫了setMeasuredDimension()
方法來儲存測量之後的寬度和高度。當我們自定義 View 的時候,也需要呼叫 setMeasuredDimension() 方法把最終的測量結果儲存起來
:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension( getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); } 複製程式碼
顯然,我們的測量依據就是widthMeasureSpec
和heightMeasureSpec
兩個引數。它們是整型的、32位變數,包含了測量模式和測量數值的資訊(按位儲存到整型變數上,包裝成整型的目的是為了節約儲存空間)。一般我們會像下面這樣來分別獲取高度和寬度的測量模式和測量數值(實際就是按位擷取):
int widthsize = MeasureSpec.getSize(widthMeasureSpec);// 測量數值 int widthmode = MeasureSpec.getMode(widthMeasureSpec);// 測量模式 int heightsize = MeasureSpec.getSize(heightMeasureSpec);// 測量數值 int heightmode = MeasureSpec.getMode(heightMeasureSpec);// 測量模式 複製程式碼
測量模式共有MeasureSpec.UNSPECIFIED
、MeasureSpec.AT_MOST
和MeasureSpec.EXACTLY
三種,分別對應二進位制數值00
、01
和10
,它們各自的含義如下:
UNSPECIFIED EXACTLY AT_MOST
這裡,我不打算詳細介紹 View 中預設測量邏輯的具體實現。它的大致邏輯是這樣的:首先我們會用getDefaultSize()
獲取預設的寬度或者高度,這個方法接收兩個引數,一個是預設的尺寸,一個測量模式。如果父控制元件沒有給它任何限制,它就使用預設的尺寸,否則使用測量數值。這裡的預設的尺寸通過getSuggestedMinimumHeight()
/getSuggestedMinimumWidth()
方法得到,它會根據背景圖片高度/寬度和mMinHeight
/mMinWidth
的值,取一個最大的值作為控制元件的高度/寬度。
所以,View 的預設的測量邏輯的實際效果是:首先 View 的大小受父容器的影響,如果父容器沒有給它限制的話,它會取背景圖片和最小的高度或者寬度中取一個最大的值作為自己的大小。
2.2 ViewGroup 的 onMeasure()
2.2.1 ViewGroup 中的方法
由於 ViewGroup 本身沒有佈局的特點,所以它沒有覆寫onMeasure()
。有自身佈局特點的,比如LinearLayout
和RelativeLayout
等都覆寫並實現了這個方法。儘管如此,ViewGroup 提供了一些方法幫助我們進行測量,首先是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); } } } 複製程式碼
這裡的邏輯比較簡單,就是對子元素進行遍歷並判斷如果指定的 View 是否位GONE
的狀態,如果不是就呼叫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); } 複製程式碼
該方法也比較容易理解,就是將子元素的佈局引數LayoutParams
取出,獲取它的寬度和高度之後,將所有信息傳遞給getChildMeasureSpec()
。這樣就得到了用於子元素佈局的childWidthMeasureSpec
和childHeightMeasureSpec
引數。然後,再呼叫子元素的measure()
方法,從而依次完成對整個 View 樹的遍歷。下面我們看下getChildMeasureSpec()
方法做了什麼操作:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) { // 首先從 spec 中取出父控制元件的測量模式和測量數值 int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); // 這裡需要保證 size 不能為負數,也就是預留給子元素的最大空間,由父元素的測量數值減去填充得到 int size = Math.max(0, specSize - padding); // 用於返回的值 int resultSize = 0; int resultMode = 0; // 根據父空間的測量模式 switch (specMode) { // 父控制元件的大小是固定的 case MeasureSpec.EXACTLY: if (childDimension >= 0) { // 子 View 指定了大小 resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { // 子元素希望大小與父控制元件相同(填滿整個父控制元件) resultSize = size; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.WRAP_CONTENT) { // 子元素希望有自己決定大小,但是不能比父控制元件大 resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; // 父控制元件的具體大小沒有尺寸限制,但是存在上限 case MeasureSpec.AT_MOST: if (childDimension >= 0) { // 子 View 指定了大小 resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { // 子控制元件希望與父控制元件大小一致,但是父控制元件的大小也是不確定的,故讓子控制元件不要比父控制元件大 resultSize = size; resultMode = MeasureSpec.AT_MOST; } else if (childDimension == LayoutParams.WRAP_CONTENT) { // 子控制元件希望自己決定大小,限制其不要比父控制元件大 resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; // 父控制元件沒有任何限制,可以設定為任意大小 case MeasureSpec.UNSPECIFIED: if (childDimension >= 0) { // 子元素設定了大小 resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { // 子控制元件希望和父控制元件一樣大,但是父控制元件多大都不確定;系統23以下返回true,以上返回size resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size; resultMode = MeasureSpec.UNSPECIFIED; } else if (childDimension == LayoutParams.WRAP_CONTENT) { resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size; resultMode = MeasureSpec.UNSPECIFIED; } break; } // 返回一個封裝好的測量結果,就是把測量數值和測量模式封裝成一個32位的整數 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } 複製程式碼
上面我們已經為這段程式碼作了非常詳細的註釋。只需要注意,這裡在獲取子元素的測量結果的時候是基於父控制元件的測量結果來的,需要根據父元素的測量模式和測量數值結合自身的佈局特點分成上面九種情況。或者可以按照下面的寫法將其劃分成下面幾種情況:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) { int specMode = MeasureSpec.getMode(spec), specSize = MeasureSpec.getSize(spec); int size = Math.max(0, specSize - padding); int resultSize = 0, resultMode = 0; if (childDimension >= 0) { // 子元素指定了具體的大小,就用子元素的大小 resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == ViewGroup.LayoutParams.MATCH_PARENT) { // 子元素希望和父控制元件一樣大,需要設定其上限,然後測量模式與父控制元件一致即可 if (specMode == MeasureSpec.EXACTLY || specMode == MeasureSpec.AT_MOST) { resultSize = size; resultMode = specMode; } else if (specMode == MeasureSpec.UNSPECIFIED) { // API23一下就是0,父控制元件沒有指定大小的時候,子控制元件只能是0;以上是size resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size; resultMode = MeasureSpec.UNSPECIFIED; } } else if (childDimension == ViewGroup.LayoutParams.WRAP_CONTENT) { // 子元素希望自己決定大小,設定其大小的上限是父控制元件的大小即可 if (specMode == MeasureSpec.EXACTLY || specMode == MeasureSpec.AT_MOST) { resultSize = size; resultMode = MeasureSpec.AT_MOST; } else if (specMode == MeasureSpec.UNSPECIFIED) { // API23一下就是0,父控制元件沒有指定大小的時候,子控制元件只能是0;以上是size resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size; resultMode = MeasureSpec.UNSPECIFIED; } } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } 複製程式碼
這兩種方式只是劃分的角度不一樣,後面的這種方法是從子元素的佈局引數上面來考慮的。另外,這裡有個sUseZeroUnspecifiedMeasureSpec
布林引數需要提及一下,會根據系統的版本來進行賦值:
sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M; 複製程式碼
也就是當系統是 API23 以下的時候的為true
. 加入這個引數的原因是,API23 之後,當父控制元件的測量模式是UNSPECIFIED
的時候,子元素可以給父控制元件提供一個可能的大小。下面是註釋的原話 ;-)
// In M and newer, our widgets can pass a "hint" value in the size // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers // know what the expected parent size is going to be, so e.g. list items can size // themselves at 1/3 the size of their container. It breaks older apps though, // specifically apps that use some popular open source libraries. 複製程式碼
2.2.2 LinearLayout 的 onMeasure()
上面我們分析的是 ViewGroup 中提供的一些方法,下面我們以 LinearLayout 為例,看一下一個標準的容器型別的控制元件是如何實現其測量的邏輯的。
下面是其onMeasure()
方法,顯然在進行測量的時候會根據其佈局的方向分別實現測量的邏輯:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mOrientation == VERTICAL) { measureVertical(widthMeasureSpec, heightMeasureSpec); } else { measureHorizontal(widthMeasureSpec, heightMeasureSpec); } } 複製程式碼
然後,我們以measureVertical()
為例,來看一下 LinearLayout 在垂直方向上面是如何進行測量的。這段程式碼比較長,我們只擷取其中的一部分來進行分析:
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) { // ... // 獲取LinearLayout的測量模式 final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); // ... mTotalLength += mPaddingTop + mPaddingBottom; int heightSize = mTotalLength; heightSize = Math.max(heightSize, getSuggestedMinimumHeight()); // ... for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final float childWeight = lp.weight; if (childWeight > 0) { // ... // 獲取一個測量的數值和測量模式 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( Math.max(0, childHeight), MeasureSpec.EXACTLY); final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin, lp.width); // 呼叫子元素進行測量 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); childState = combineMeasuredStates(childState, child.getMeasuredState() & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); } final int margin =lp.leftMargin + lp.rightMargin; final int measuredWidth = child.getMeasuredWidth() + margin; maxWidth = Math.max(maxWidth, measuredWidth); boolean matchWidthLocally = widthMode != MeasureSpec.EXACTLY && lp.width == LayoutParams.MATCH_PARENT; alternativeMaxWidth = Math.max(alternativeMaxWidth, matchWidthLocally ? margin : measuredWidth); allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT; final int totalLength = mTotalLength; // 將寬度增加到 mTotalLength 上 mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child)); } mTotalLength += mPaddingTop + mPaddingBottom; // ... maxWidth += mPaddingLeft + mPaddingRight; maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); // 最終確定測量的大小 setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); // ... } 複製程式碼
上面是 LinearLayout 在垂直方向上面的測量的過程,在測量的時候會根據子元素的佈局將子元素的測量高度新增到mTotalLength
上,然後再加上填充的大小,作為最終的測量結果。
3、layout()
layout()
用於確定控制元件的位置,它提供了onLayout()
來交給字類實現,同樣我們在自定義控制元件的時候只要實現onLayout()
方法即可。在我們自定義 View 的時候,如果定義的是非 ViewGroup 型別的控制元件,一般是不需要覆寫onLayout()
方法的。
下面我們先看一下layout()
方法在 View 中的實現:
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); // ... } // ... } 複製程式碼
這裡會呼叫setFrame()
方法,它的主要作用是根據新的佈局引數和老的佈局引數做一個對比,以判斷控制元件的大小是否發生了變化,如果變化了的話就呼叫invalidate()
方法並傳入引數true
,以表明繪圖的快取也發生了變化。這裡就不給出這個方法的具體實現了。然後注意到,在layout()
方法中會回撥onLayout()
方法來完成各個控制元件的位置的確定。
對於 ViewGroup,它重寫了layout()
並在其中呼叫了 View 中的layout()
方法,不過整體並沒有做太多的邏輯。與測量過程類似,ViewGroup 並沒有實現onLayout
方法。同樣,對於 ViewGroup 型別的控制元件,我們還是以 LinearLayout 為例說明一下onLayout()
的實現邏輯:
與測量過程類似,LinearLayout 在 layout 的時候也根據佈局的方向分成兩種情形:
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); } } 複製程式碼
這裡我們仍以垂直方向的方法為例。與測量的過程相比,layout 的過程的顯得簡單、清晰得多:
void layoutVertical(int left, int top, int right, int bottom) { // ... // 根據控制元件的 gravity 特點得到頂部的位置 switch (majorGravity) { case Gravity.BOTTOM: childTop = mPaddingTop + bottom - top - mTotalLength; break; case Gravity.CENTER_VERTICAL: childTop = mPaddingTop + (bottom - top - mTotalLength) / 2; break; case Gravity.TOP: default: childTop = mPaddingTop; break; } // 遍歷子控制元件 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; // 本質上呼叫子控制元件的 layout() 方法 setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child); i += getChildrenSkipCount(child, i); } } } 複製程式碼
因為佈局方向是垂直方向的,所以在對子元素進行遍歷之前,先對自身的頂部的位置進行計算,然後再依次遍歷子元素,並對頂部的高度不斷疊加,最後呼叫setChildFrame()
方法:
private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); } 複製程式碼
這樣就完成了對整個 View 樹的layout()
方法的呼叫。
4、draw()
View 的draw()
方法實現的邏輯也很清晰。在繪製的過程會按照如下的步驟進行:
- 繪製背景
- 儲存 canvas
- 繪製自身的內容
- 繪製子控制元件
- 繪製 View 的褪色邊緣,比如陰影效果之類的
- 繪製裝飾,比如滾動條之類的
View 中提供了onDraw()
方法用來完成對自身的內容的繪製,所以,我們自定義 View 的時候只要重寫這個方法就可以了。當我們要自定義一個 ViewGroup 型別的控制元件的時候,一般是不需要重寫onDraw()
方法的,因為它只需要遍歷子控制元件並依次呼叫它們的draw()
方法就可以了。(當然,如果非要實現的話,也是可以的。)
下面是這部分程式碼,程式碼的註釋中也詳細註釋了每個步驟的邏輯:
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; // 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); 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; } // ... } 複製程式碼
注意到在上面的方法中會呼叫dispatchDraw(canvas)
方法來分發繪製事件給子控制元件來完成整個 View 樹的繪製。在 View 中,這是一個空的方法,ViewGroup 覆寫了這個方法,並在其中呼叫drawChild()
來完成對指定的 View 的draw()
方法的呼叫:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime); } 複製程式碼
而對於 LinearLayout 這樣本身沒有繪製需求的控制元件,沒有覆寫onDraw()
和dispatchDraw(canvas)
等方法,因為 View 和 ViewGroup 中提供的功能已經足夠使用。
總結:
上文中,我們介紹了在 Android 系統中整個 View 樹的工作的流程,從 DecorView 被載入到視窗中,到測量、佈局和繪製三個方法的實現。本質上整個工作的流程就是對 View 樹的一個深度優先的遍歷過程。