文末有免費福利哦面試
當咱們調用 startActivity()
方法的時候,會調用到 ActivityThread
中的 performLaunchActivity()
獲取一個 Activity 實例, 並在 Instrumentation
的 callActivityOnCreate()
方法中調用 Activity 的 onCreate()
完成 DecorView 的建立。這樣咱們就獲取了一個 Activity 的實例,而後咱們調用 handleResumeActivity()
來回調 Activity 的 onResume()
:canvas
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()
三個方法必定不會陌生,前面的三個方法與後面的三個方法之間的關係就是:後面的三個方法會被前面的三個方法調用,本質上就是提供給用戶用來自定義的方法。下面咱們就看下這三個方法究竟各自作了什麼操做,固然,咱們儘量從自定義控件的角度來分析,由於這對一個開發者可能幫助更大。性能優化
文末有免費福利哦架構
View 的大小不只由自身所決定,同時也會受到父控件的影響,爲了咱們的控件能更好的適應各類狀況,通常會本身進行測量。在上面咱們提到了 measure()
方法,它是用來測量 View 的大小的,但實際上測量的主要工做是交給 onMeasure()
方法的。在 View 中,onMeasure()
是一個 protected
的方法,顯然它設計的目的就是:提供給子 View 按照父容器提供的限制條件,控制自身的大小,實現本身大小的測量邏輯。因此,當咱們自定義一個控件的時候,只會去覆寫 onMeasure()
而不去覆寫 measure()
方法。app
在 Android 中,咱們的控件分紅 View 和 ViewGroup 兩種類型。根據上面的分析,對 View 的測量,咱們能夠得出以下結論:在 Android 中,ViewGroup 會根據其自身的佈局特色,把限制條件封裝成 widthMeasureSpec
和 heightMeasureSpec
兩個參數傳遞給子元素;而後,在子元素中根據這兩個參數來調整自身的大小。因此,ViewGroup 的 measure()
方法會根據其佈局特性的不一樣而不一樣;而 View 的 measure()
,不論其父容器是哪一種類型,只根據 widthMeasureSpec
和 heightMeasureSpec
決定。ide
下面咱們來看一下 onMeasure()
在 View 和 ViewGroup 中的不一樣表現形式。佈局
下面是 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
,它們各自的含義以下:
這裏,我不打算詳細介紹 View 中默認測量邏輯的具體實現。它的大體邏輯是這樣的:首先咱們會用 getDefaultSize()
獲取默認的寬度或者高度,這個方法接收兩個參數,一個是默認的尺寸,一個測量模式。若是父控件沒有給它任何限制,它就使用默認的尺寸,不然使用測量數值。這裏的默認的尺寸經過 getSuggestedMinimumHeight()
/getSuggestedMinimumWidth()
方法獲得,它會根據背景圖片高度/寬度和 mMinHeight
/mMinWidth
的值,取一個最大的值做爲控件的高度/寬度。
因此,View 的默認的測量邏輯的實際效果是:首先 View 的大小受父容器的影響,若是父容器沒有給它限制的話,它會取背景圖片和最小的高度或者寬度中取一個最大的值做爲本身的大小。
因爲 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. 複製代碼
上面咱們分析的是 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
上,而後再加上填充的大小,做爲最終的測量結果。
文末有免費福利哦
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()
方法的調用。
View 的 draw()
方法實現的邏輯也很清晰。在繪製的過程會按照以下的步驟進行:
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 樹的一個深度優先的遍歷過程。
想學習更多Android知識,請加入Android技術開發企鵝交流 7520 16839
進羣與大牛們一塊兒討論,還可獲取Android高級架構資料、源碼、筆記、視頻
包括 高級UI、Gradle、RxJava、小程序、Hybrid、移動架構、React Native、性能優化等全面的Android高級實踐技術講解性能優化架構思惟導圖,和BATJ面試題及答案!
羣裏免費分享給有須要的朋友,但願可以幫助一些在這個行業發展迷茫的,或者想系統深刻提高以及困於瓶頸的朋友,在網上博客論壇等地方少花些時間找資料,把有限的時間,真正花在學習上,因此我在這免費分享一些架構資料及給你們。但願在這些資料中都有你須要的內容。