編輯:關於 Android 程式設計
還記得先前那篇《Android 應用 setContentView 與 LayoutInflater 加載解析機制源碼分析》嗎?我們當時剖析了 Activity 界面加載顯示的基本原理,最終得出的關係正如下圖所示:

整個流程的核心程式碼位於 ViewRootImpl 類別的 performTraversals 方法中:
private void performTraversals() { ...... //最外層的根視圖的widthMeasureSpec和heightMeasureSpec由來 //lp.width和lp.height在創建ViewGroup實例時等於MATCH_PARENT int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); ...... mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); ...... mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight()); ...... mView.draw(canvas); ...... }
/** * Figures out the measure spec for the root view in a window based on it's * layout params. * * @param windowSize * The available width or height of the window * * @param rootDimension * The layout params for one dimension (width or height) of the * window. * * @return The measure spec to use to measure the root view. */ private static int getRootMeasureSpec(int windowSize, int rootDimension) { int measureSpec; switch (rootDimension) { case ViewGroup.LayoutParams.MATCH_PARENT: // Window can't resize. Force root view to be windowSize. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); break; ...... } return measureSpec; }
從註解可知,這個方法是用來測量 Root View 的。代入參數後,程式碼走的是 MATCH_PARENT 分支,以 MeasureSpec.makeMeasureSpec 組裝出一個 MeasureSpec,其 specMode 為 EXACTLY、specSize 為 windowSize——這正是根視圖總是填滿全屏的原因。其中的 mView 就是 View 物件。整個流程大致如下圖:

接下來,我們就依序深入剖析 View 繪製的三大流程(以下分析基於 Android 5.1.1 API 22 源碼)。
整個 View 樹的 measure 流程如下圖:

先看 View 的 measure 方法:
/** * This is called to find out how big a view should be. The parent * supplies constraint information in the width and height parameters. * * The actual measurement work of a view is performed in * {@link #onMeasure(int, int)}, called by this method. Therefore, only * {@link #onMeasure(int, int)} can and must be overridden by subclasses. * * @param widthMeasureSpec Horizontal space requirements as imposed by the * parent * @param heightMeasureSpec Vertical space requirements as imposed by the * parent * * @see #onMeasure(int, int) */ //final方法,子類不可重寫 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { ...... //回調onMeasure()方法 onMeasure(widthMeasureSpec, heightMeasureSpec); ...... }
註解透露了不少關鍵資訊:它負責為整棵 View 樹計算實際大小,再設定實際的高與寬。每個 View 控制項的最終尺寸,都由父視圖與自身共同決定;真正的測量工作發生在 onMeasure 方法中,因此 View 的子類需要覆寫 onMeasure。這是因為 measure 被宣告為 final、不允許覆寫,所以子類只能透過覆寫 onMeasure 來實作自己的測量邏輯。
這個方法的兩個參數都由父 View 傳入,代表父 View 的規格。每個參數由兩部分組成:高 16 位表示 MODE,定義在 MeasureSpec 類(View 的內部類)中,共三種——MeasureSpec.EXACTLY 表示確切大小,MeasureSpec.AT_MOST 表示最大上限,MeasureSpec.UNSPECIFIED 表示不確定;低 16 位則表示 size,也就是父 View 的大小。對於系統 Window 的 DecorView 而言,其 Mode 一般為 MeasureSpec.EXACTLY,size 分別對應螢幕寬高;而子 View 的大小則由父 View 與子 View 共同決定。
可見 measure 最終回調了 View 的 onMeasure 方法,來看看它的原始碼:
/** * Measure the view and its content to determine the measured width and the * measured height. This method is invoked by {@link #measure(int, int)} and * should be overriden by subclasses to provide accurate and efficient * measurement of their contents. * * CONTRACT: When overriding this method, you * must call {@link #setMeasuredDimension(int, int)} to store the * measured width and height of this view. Failure to do so will trigger an * IllegalStateException, thrown by * {@link #measure(int, int)}. Calling the superclass' * {@link #onMeasure(int, int)} is a valid use. * * The base class implementation of measure defaults to the background size, * unless a larger size is allowed by the MeasureSpec. Subclasses should * override {@link #onMeasure(int, int)} to provide better measurements of * their content. * * If this method is overridden, it is the subclass's responsibility to make * sure the measured height and width are at least the view's minimum height * and width ({@link #getSuggestedMinimumHeight()} and * {@link #getSuggestedMinimumWidth()}). * * @param widthMeasureSpec horizontal space requirements as imposed by the parent. * The requirements are encoded with * {@link android.view.View.MeasureSpec}. * @param heightMeasureSpec vertical space requirements as imposed by the parent. * The requirements are encoded with * {@link android.view.View.MeasureSpec}. * * @see #getMeasuredWidth() * @see #getMeasuredHeight() * @see #setMeasuredDimension(int, int) * @see #getSuggestedMinimumHeight() * @see #getSuggestedMinimumWidth() * @see android.view.View.MeasureSpec#getMode(int) * @see android.view.View.MeasureSpec#getSize(int) */ //View的onMeasure默認實現方法 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }
註解其實已經寫得非常詳盡,連自訂 View 覆寫該方法的操作指引都一應俱全,這裡便不再贅述。
對於非 ViewGroup 的一般 View,透過上述預設的 onMeasure 即可完成測量。當然你也可以覆寫 onMeasure 並呼叫 setMeasuredDimension 來設定任意大小,但一般不建議這麼做——至於緣由,等分析完後你自然會明白。
可以注意到,onMeasure 的預設實作僅呼叫了 setMeasuredDimension,而這是個關鍵方法:它為 View 的成員變數 mMeasuredWidth 與 mMeasuredHeight 賦值。measure 的主要目的,就是為 View 樹中每個 View 的這兩個變數賦值,因此一旦它們被賦值,就意味著該 View 的測量工作宣告完成。既然預設尺寸是透過 getDefaultSize 回傳的,我們就來看看它的源碼:
public static int getDefaultSize(int size, int measureSpec) { int result = size; //通過MeasureSpec解析獲取mode與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; }
可以看到,當 specMode 為 AT_MOST 或 EXACTLY 時便回傳 specSize,這就是系統的預設規格。
回到 onMeasure,其中 getDefaultSize 的 widthMeasureSpec 與 heightMeasureSpec 都由父 View 傳入,而 getSuggestedMinimumWidth 與 getSuggestedMinimumHeight 則是 View 的方法:
protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); } protected int getSuggestedMinimumHeight() { return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); }
可見建議的最小寬度與高度,是由 View 的背景尺寸與透過 miniXXX 屬性設定的值共同決定的。
至此,一次最基礎的元素 View 測量便完成了。由於 View 是層層嵌套的,而 measure 又是遞歸傳遞的,因此每個 View 都得測量一次。能承載嵌套的 View 一般都是 ViewGroup 的子類,所以 ViewGroup 定義了 measureChildren、measureChild、measureChildWithMargins 等方法來測量子視圖。其中 measureChildren 內部只是迴圈呼叫 measureChild,而 measureChild 與 measureChildWithMargins 的差別在於是否把 margin 與 padding 一併計入子視圖尺寸。下面以稍複雜的 measureChildWithMargins 為例:
/** * Ask one of the children of this view to measure itself, taking into * account both the MeasureSpec requirements for this view and its padding * and margins. The child must have MarginLayoutParams The heavy lifting is * done in getChildMeasureSpec. * * @param child The child to measure * @param parentWidthMeasureSpec The width requirements for this view * @param widthUsed Extra space that has been used up by the parent * horizontally (possibly by other children of the parent) * @param parentHeightMeasureSpec The height requirements for this view * @param heightUsed Extra space that has been used up by the parent * vertically (possibly by other children of the parent) */ protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { //獲取子視圖的LayoutParams final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); //調整MeasureSpec //通過這兩個參數以及子視圖本身的LayoutParams來共同決定子視圖的測量規格 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); //調運子View的measure方法,子View的measure中會回調子View的onMeasure方法 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); }
該方法的參數說明,註解已交代得相當清楚。它做的事,是把父視圖提供的 measureSpec 參數,結合自身的 LayoutParams 進行調整,再呼叫 child.measure(),而具體的調整邏輯由 getChildMeasureSpec 完成。我們接著看它的原始碼:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) { //獲取當前Parent View的Mode和Size int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); //獲取Parent size與padding差值(也就是Parent剩余大小),若差值小於0直接返回0 int size = Math.max(0, specSize - padding); //定義返回值存儲變量 int resultSize = 0; int resultMode = 0; //依據當前Parent的Mode進行switch分支邏輯 switch (specMode) { // Parent has imposed an exact size on us //默認Root View的Mode就是EXACTLY case MeasureSpec.EXACTLY: if (childDimension >= 0) { //如果child的layout_wOrh屬性在xml或者java中給予具體大於等於0的數值 //設置child的size為真實layout_wOrh屬性值,mode為EXACTLY resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果child的layout_wOrh屬性在xml或者java中給予MATCH_PARENT // Child wants to be our size. So be it. //設置child的size為size,mode為EXACTLY resultSize = size; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果child的layout_wOrh屬性在xml或者java中給予WRAP_CONTENT //設置child的size為size,mode為AT_MOST // Child wants to determine its own size. It can't be // bigger than us. resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; ...... //其他Mode分支類似 } //將mode與size通過MeasureSpec方法整合為32位整數返回 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); }
可以看到,getChildMeasureSpec 的邏輯是:先從父 View 提供的 MeasureSpec 解析出 specMode 與 specSize,再依據計算出的 specMode 及子 View 的 childDimension(layout_width 或 layout_height)算出自身的 measureSpec。若本身還含有子視圖,這算出來的 measureSpec 便會作為呼叫子視圖 measure 的參數,同時也作為自身呼叫 setMeasuredDimension 的參數;若不包含子視圖,則預設最終會走到 onMeasure 的預設實作,並一路調用至 setMeasuredDimension。
由此可見,onMeasure 的參數正是這樣一步步算出來的。同時也能看出,最終決定 View 測量尺寸的是 setMeasuredDimension 方法,因此我們固然可以透過它把 mMeasuredWidth 與 mMeasuredHeight 設為固定值;但一個好的自訂 View 更應依據子視圖的 measureSpec 來設定這兩個值,如此靈活性更高——這也就是前面提到「onMeasure 不宜寫死值」的原因。
唯有當 setMeasuredDimension 完成賦值後,View 的 mMeasuredWidth 與 mMeasuredHeight 才會有具體數值。因此,如果你想透過 getMeasuredWidth() 與 getMeasuredHeight() 取得測量後的寬高,就必須保證這兩個方法在 onMeasure 流程之後才被呼叫,否則取不到有效值。
還記得先前那篇 setContentView 與 LayoutInflater 分析文章 3-3 小節探討過的「inflate 加載布局時指定大小失效」問題嗎?當時只給了結論,如今有了完整的成因分析,相信不需再多解釋了。
至此,View 繪製流程的第一步分析完成。相對而言它確實有些複雜,接著做個小結。
由上述分析可知,measure 過程本質上是從頂層父 View 向子 View 遞歸呼叫 view.measure(其中又回調 onMeasure)的過程。核心要點如下:
MeasureSpec(View 的內部類)為 int 型,由高 16 位的規格模式 specMode 與低 16 位的具體尺寸 specSize 組成,其中 specMode 有三種取值: MeasureSpec.EXACTLY //確定模式,父View希望子View的大小是確定的,由specSize決定; MeasureSpec.AT_MOST //最多模式,父View希望子View的大小最多是specSize指定的值; MeasureSpec.UNSPECIFIED //未指定模式,父View完全依據子View的設計值來決定;
View 的 measure 方法是 final 的,不允許覆寫,子類只能覆寫 onMeasure 來完成自己的測量邏輯。 最頂層 DecorView 測量時的 MeasureSpec 由 ViewRootImpl 的 getRootMeasureSpec 方法決定(LayoutParams 寬高皆為 MATCH_PARENT,specMode 為 EXACTLY,specSize 為實體螢幕大小)。 ViewGroup 提供了 measureChild、measureChild 與 measureChildWithMargins 等方法,簡化了父子 View 的尺寸計算。 只要是 ViewGroup 的子類,其 LayoutParams 就必須繼承自 MarginLayoutParams,否則無法使用 layout_margin 參數。 View 的布局大小由父 View 與子 View 共同決定。 透過 getMeasuredWidth() 與 getMeasuredHeight() 取得測量寬高時,必須確保在 onMeasure 流程之後呼叫才有效。
如背景所述,當 ViewRootImpl 的 performTraversals 中 measure 執行完畢後,會接著執行 mView.layout:
private void performTraversals() { ...... mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight()); ...... }
可見 layout 接收四個參數,分別代表相對於 Parent 的左、上、右、下座標,其中左上皆為 0,右下則是剛測量出的 width 與 height。於是又回到 View 的 layout(int l, int t, int r, int b) 方法中實作具體邏輯,接著我們開始分析 View 的 layout 過程。整棵 View 樹的 layout 遞歸流程如下圖:

layout 同樣是遞歸結構,先看 ViewGroup 的 layout 方法:
@Override public final void layout(int l, int t, int r, int b) { ...... super.layout(l, t, r, b); ...... }
可以看到,ViewGroup 的 layout 實際上仍是呼叫父類 View 的 layout 方法,因此來看 View 的 layout 源碼:
public void layout(int l, int t, int r, int b) { ...... //實質都是調用setFrame方法把參數分別賦值給mLeft、mTop、mRight和mBottom這幾個變量 //判斷View的位置是否發生過變化,以確定有沒有必要對當前的View進行重新layout boolean changed = isLayoutModeOptical(mParent) ? setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); //需要重新layout if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { //回調onLayout onLayout(changed, l, t, r, b); ...... } ...... }
類似 measure 過程,layout 也回調了 onLayout 方法。
對比 View 與 ViewGroup 的 layout 方法可以發現:View 的 layout 可在子類覆寫,而 ViewGroup 的 layout 是 final、不可覆寫的,也就是說 ViewGroup 只能透過覆寫 onLayout 來定制。我們來看 ViewGroup 的 onLayout:
@Override protected abstract void onLayout(boolean changed, int l, int t, int r, int b);
竟然是個抽象方法!這意味著所有 ViewGroup 的子類都必須覆寫它。因此在自訂 ViewGroup 控制項時,onLayout 搭配 onMeasure 一起使用,就能實現複雜的自訂布局:先呼叫 onMeasure 測量,再在 onLayout 中動態取得各子 View 的測量大小並安排位置。覆寫 onLayout 的常見做法,就是寫一個 for 迴圈,逐一呼叫每個子視圖的 layout(l, t, r, b),傳入不同的參數來確定它們在父視圖中的位置。
再看 View 的 onLayout:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { }
是個空方法,沒什麼可看的。既然這樣,我們就分析一個現成的 ViewGroup 子類——LinearLayout,以下是它 onLayout 的部分程式碼:
public class LinearLayout extends ViewGroup { @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); } } }
可以看到,LinearLayout 的 layout 會依 Vertical 與 Horizontal 分流,這對應到 XML 布局中的 orientation 屬性。我們以 VERTICAL 模式為例,說明 ViewGroup 覆寫 onLayout 的一般步驟,以下是 layoutVertical 的源碼:
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 //計算父窗口推薦的子View寬度 final int width = right - left; //計算父窗口推薦的子View右側位置 int childRight = width - mPaddingRight; // Space available for child //child可使用空間大小 int childSpace = width - paddingLeft - mPaddingRight; //通過ViewGroup的getChildCount方法獲取ViewGroup的子View個數 final int count = getVirtualChildCount(); //獲取Gravity屬性設置 final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; //依據majorGravity計算childTop的位置值 switch (majorGravity) { case Gravity.BOTTOM: // mTotalLength contains the padding already childTop = mPaddingTop + bottom - top - mTotalLength; break; // mTotalLength contains the padding already 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) { //LinearLayout中其子視圖顯示的寬和高由measure過程來決定的,因此measure過程的意義就是為layout過程提供視圖顯示范圍的參考值 final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); //獲取子View的LayoutParams 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); //依據不同的absoluteGravity計算childLeft位置 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; //通過垂直排列計算調運child的layout設置child的位置 setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child); i += getChildrenSkipCount(child, i); } } }
從 LinearLayout 的 onLayout 實作可以看出,一般情況下 layout 會參考 measure 階段算出的 mMeasuredWidth 與 mMeasuredHeight 來安排子 View 的位置,但這並非強制——measure 的結果甚至可能毫無用武之地,特別是對那些子 View 數量、位置、大小都固定的自訂 ViewGroup 而言,此時完全可以略過整個 measure 過程,僅依 layout 傳入的 4 個參數來安排每個子 View 的位置。
說到這裡,就不得不提 getWidth()、getHeight() 與 getMeasuredWidth()、getMeasuredHeight() 這兩對方法的區別(前面已提到後兩者須在 onMeasure 之後才有效)。而 getWidth() 與 getHeight() 則必須在 layout(int l, int t, int r, int b) 執行之後才有效。來看 View 源碼中的實作:
public final int getMeasuredWidth() { return mMeasuredWidth & MEASURED_SIZE_MASK; } public final int getMeasuredHeight() { return mMeasuredHeight & MEASURED_SIZE_MASK; } public final int getWidth() { return mRight - mLeft; } public final int getHeight() { return mBottom - mTop; } public final int getLeft() { return mLeft; } public final int getRight() { return mRight; } public final int getTop() { return mTop; } public final int getBottom() { return mBottom; }
這也解釋了為何某些情況下 getWidth() 與 getMeasuredWidth()、getHeight() 與 getMeasuredHeight() 會得到不同的值,此處不再贅述。至此,View 的 layout 過程分析告一段落,接著做個總結。
整個 layout 過程較易理解:它同樣是從頂層父 View 向子 View 遞歸呼叫 view.layout 的過程,即父 View 依據上一步 measure 子 View 所得的尺寸與布局參數,把子 View 放到合適的位置上。核心要點如下:
View.layout 可被覆寫;ViewGroup.layout 為 final 不可覆寫;ViewGroup.onLayout 為 abstract,子類必須覆寫以實作自己的定位邏輯。 measure 完成後得到的是每個 View 測量後的 measuredWidth 與 measuredHeight;layout 完成後得到的則是位置分配後的 mLeft、mTop、mRight、mBottom,這些值都是相對於父 View 而言的。 凡是 layout_XXX 布局屬性,基本都針對含有子 View 的 ViewGroup;對一個沒有父容器的 View 設定相關 layout_XXX 屬性是毫無意義的。 透過 getWidth() 與 getHeight() 取得寬高時,必須確保在 onLayout 流程之後呼叫才有效。如背景所述,當 performTraversals 中 measure 與 layout 完成後,會接著執行 mView.draw:
private void performTraversals() { ...... final Rect dirty = mDirty; ...... canvas = mSurface.lockCanvas(dirty); ...... mView.draw(canvas); ...... }
draw 同樣在 ViewRootImpl 的 performTraversals() 內部呼叫,順序在 measure() 與 layout() 之後。此處的 mView 對 Activity 而言就是 PhoneWindow.DecorView;ViewRootImpl 會建立一個 Canvas 物件,再呼叫 View 的 draw() 來執行具體的繪製工作,於是又回到 ViewGroup 與 View 的樹狀遞歸 draw 過程。遞歸 draw 流程如下圖:

由於 ViewGroup 並未覆寫 View 的 draw 方法,這裡直接從 View 的 draw 方法開始分析:
public void draw(Canvas canvas) { ...... /* * 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 ...... if (!dirtyOpaque) { drawBackground(canvas); } // skip step 2 & 5 if possible (common case) ...... // Step 2, save the canvas' layers ...... if (drawTop) { canvas.saveLayer(left, top, right, top + length, null, flags); } ...... // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 5, draw the fade effect and restore layers ...... if (drawTop) { matrix.setScale(1, fadeHeight * topFadeStrength); matrix.postTranslate(left, top); fade.setLocalMatrix(matrix); p.setShader(fade); canvas.drawRect(left, top, right, top + length, p); } ...... // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); ...... }
draw 方法看似繁複,但源碼註解已把整個過程切分成 6 步。註解提到("skip step 2 & 5 if possible (common case)")第 2、5 步在常見情況下可略過,因此我們重點看其餘四步。
第一步,繪製 View 的背景。
draw 透過呼叫 drawBackground(canvas) 完成背景繪製,來看它的源碼:
private void drawBackground(Canvas canvas) { //獲取xml中通過android:background屬性或者代碼中setBackgroundColor()、setBackgroundResource()等方法進行賦值的背景Drawable final Drawable background = mBackground; ...... //根據layout過程確定的View位置來設置背景的繪制區域 if (mBackgroundSizeChanged) { background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); mBackgroundSizeChanged = false; rebuildOutline(); } ...... //調用Drawable的draw()方法來完成背景的繪制工作 background.draw(canvas); ...... }
第三步,繪製 View 的內容。
這裡呼叫了 View 的 onDraw() 方法,來看它的源碼(ViewGroup 同樣未覆寫):
/** * Implement this to do your drawing. * * @param canvas the canvas on which the background will be drawn */ protected void onDraw(Canvas canvas) { }
是個空方法。由於每個 View 的內容各不相同,具體邏輯需由子類去實作。
第四步,繪製當前 View 的所有子 View(若無子 View 則略過)。
來看 draw 中的 dispatchDraw(canvas) 方法:
/** * Called by draw to draw the child views. This may be overridden * by derived classes to gain control just before its children are drawn * (but after its own view has been drawn). * @param canvas the canvas on which to draw the view */ protected void dispatchDraw(Canvas canvas) { }
可見 View 的 dispatchDraw() 是空方法,註解也說明含有子類的 View 需覆寫它,因此有必要看看 ViewGroup 的 dispatchDraw(這也正是「只有 ViewGroup 才需要繪製子 View」的原因):
@Override protected void dispatchDraw(Canvas canvas) { ...... final int childrenCount = mChildrenCount; final View[] children = mChildren; ...... for (int i = 0; i < childrenCount; i++) { ...... if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { more |= drawChild(canvas, child, drawingTime); } } ...... // Draw any disappearing views that have animations if (mDisappearingChildren != null) { ...... for (int i = disappearingCount; i >= 0; i--) { ...... more |= drawChild(canvas, child, drawingTime); } } ...... }
的確,ViewGroup 覆寫了 dispatchDraw(),內部會遍歷每個子 View 並呼叫 drawChild(),來看 drawChild:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime); }
可見 drawChild() 呼叫了子 View 的 draw()。也就是說,ViewGroup 已為我們實作了 dispatchDraw() 的功能,一般不需覆寫,但可以在父類函數基礎上覆寫以定制具體行為。
第六步,繪製 View 的滾動條。
這裡呼叫了 onDrawScrollBars() 方法:
/** * Request the drawing of the horizontal and the vertical scrollbar. The * scrollbars are painted only if they have been awakened first. * * @param canvas the canvas on which to draw the scrollbars * * @see #awakenScrollBars(int) */ protected final void onDrawScrollBars(Canvas canvas) { //繪制ScrollBars分析不是我們這篇的重點,所以暫時不做分析 ...... }
可見其實任何一個 View 都具備(水平與垂直)滾動條,只是通常沒讓它顯示出來而已。至此,View 的 draw 繪製源碼分析完畢,接著做個總結。
繪製過程就是把 View 物件畫到螢幕上,整個 draw 需注意以下細節:
若該 View 是一個 ViewGroup,則需遞歸繪製其所有子 View。 View 預設不繪製任何內容,真正的繪製都需自己在子類中實作。 View 的繪製是藉由 onDraw 傳入的 Canvas 類來進行的。 應區分 View 動畫與 ViewGroup 布局動畫:前者指 View 自身的動畫,可透過 setAnimation 添加;後者專指 ViewGroup 顯示內部子視圖時的動畫,可在 XML 中對 ViewGroup 設定 layoutAnimation 屬性(例如讓 LinearLayout 的子 View 以逐行、隨機、下落等效果出現)。 在取得畫布剪切區(每個 View 的 draw 中傳入的 Canvas)時,系統會自動處理掉 padding,子 View 取得 Canvas 時無需理會這些邏輯,只需專注如何繪製。 預設情況下,子 View 的 ViewGroup.drawChild 繪製順序與子 View 被添加的順序一致,但你也可覆寫 ViewGroup.getChildDrawingOrder() 提供不同順序。你可能注意到,前面分析三步繪製流程時,末尾都呼叫了一個叫 invalidate 的方法。它是什麼?為何出現頻率如此之高?很簡單,拿出來分析一番即可。
來看 View 類中的一些 invalidate 方法(ViewGroup 未覆寫這些方法):
/** * Mark the area defined by dirty as needing to be drawn. If the view is * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some * point in the future. * This must be called from a UI thread. To call from a non-UI thread, call * {@link #postInvalidate()}. * * @param dirty the rectangle representing the bounds of the dirty region */ //public,只能在UI Thread中使用,別的Thread用postInvalidate方法,View是可見的才有效,回調onDraw方法,針對局部View public void invalidate(Rect dirty) { final int scrollX = mScrollX; final int scrollY = mScrollY; //實質還是調運invalidateInternal方法 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, dirty.right - scrollX, dirty.bottom - scrollY, true, false); } /** * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. * If the view is visible, {@link #onDraw(android.graphics.Canvas)} will be called at some * point in the future. * This must be called from a UI thread. To call from a non-UI thread, call * {@link #postInvalidate()}. * * @param l the left position of the dirty region * @param t the top position of the dirty region * @param r the right position of the dirty region * @param b the bottom position of the dirty region */ //public,只能在UI Thread中使用,別的Thread用postInvalidate方法,View是可見的才有效,回調onDraw方法,針對局部View public void invalidate(int l, int t, int r, int b) { final int scrollX = mScrollX; final int scrollY = mScrollY; //實質還是調運invalidateInternal方法 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); } /** * Invalidate the whole view. If the view is visible, * {@link #onDraw(android.graphics.Canvas)} will be called at some * point in the future. * This must be called from a UI thread. To call from a non-UI thread, call * {@link #postInvalidate()}. */ //public,只能在UI Thread中使用,別的Thread用postInvalidate方法,View是可見的才有效,回調onDraw方法,針對整個View public void invalidate() { //invalidate的實質還是調運invalidateInternal方法 invalidate(true); } /** * This is where the invalidate() work actually happens. A full invalidate() * causes the drawing cache to be invalidated, but this function can be * called with invalidateCache set to false to skip that invalidation step * for cases that do not need it. * * @param invalidateCache Whether the drawing cache for this view should be * invalidated as well. */ //default的權限,只能在UI Thread中使用,別的Thread用postInvalidate方法,View是可見的才有效,回調onDraw方法,針對整個View void invalidate(boolean invalidateCache) { //實質還是調運invalidateInternal方法 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); } //!!!!!!看見沒有,這是所有invalidate的終極調運方法!!!!!! void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, boolean fullInvalidate) { ...... // Propagate the damage rectangle to the parent view. final AttachInfo ai = mAttachInfo; final ViewParent p = mParent; if (p != null && ai != null && l < r && t < b) { final Rect damage = ai.mTmpInvalRect; //設置刷新區域 damage.set(l, t, r, b); //傳遞調運Parent ViewGroup的invalidateChild方法 p.invalidateChild(this, damage); } ...... }
可見 View 的 invalidate(invalidateInternal)本質上把要刷新的區域交給父 ViewGroup 的 invalidateChild 方法處理。invalidate 中呼叫父 View 的 invalidateChild,這是一個從當前節點向上級父 View 回溯的過程,每一層父 View 都會把自己的顯示區域與傳入的刷新 Rect 求交集。來看 ViewGroup 的 invalidateChild:
public final void invalidateChild(View child, final Rect dirty) { ViewParent parent = this; final AttachInfo attachInfo = mAttachInfo; ...... do { ...... //循環層層上級調運,直到ViewRootImpl會返回null parent = parent.invalidateChildInParent(location, dirty); ...... } while (parent != null); }
這個過程最終會傳遞到 ViewRootImpl 的 invalidateChildInParent 方法而結束,來看它:
@Override public ViewParent invalidateChildInParent(int[] location, Rect dirty) { ...... //View調運invalidate最終層層上傳到ViewRootImpl後最終觸發了該方法 scheduleTraversals(); ...... return null; }
可以看到,這個方法直接回傳 null,正好終結了上面 ViewGroup 中那個 do while 迴圈。注意到這裡呼叫的 scheduleTraversals 了嗎?它會透過 Handler 的 Runnable 送出一個非同步訊息,呼叫 doTraversal,最終觸發 performTraversals() 執行重繪。開頭背景提過,performTraversals 正是整棵 View 樹開始繪製的起點。因此,View 呼叫 invalidate 的本質,是把刷新請求層層上傳,直到 ViewRootImpl 觸發 scheduleTraversals,於是整棵 View 樹便依前面分析的繪製流程重新走一遍。至此,invalidate 的原理分析完成。
前面提到 invalidate 只能在 UI Thread 執行,其他執行緒需改用 postInvalidate,來看它的源碼:
public void postInvalidate() { postInvalidateDelayed(0); }
再看它呼叫的 postInvalidateDelayed:
public void postInvalidateDelayed(long delayMilliseconds) { // We try only with the AttachInfo because there's no point in invalidating // if we are not attached to our window final AttachInfo attachInfo = mAttachInfo; //核心,實質就是調運了ViewRootImpl.dispatchInvalidateDelayed方法 if (attachInfo != null) { attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); } }
再看 ViewRootImpl 的 dispatchInvalidateDelayed:
public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); mHandler.sendMessageDelayed(msg, delayMilliseconds); }
可以看到,它透過 ViewRootImpl 的 Handler 送出了一條 MSG_INVALIDATE 訊息,追蹤其處理:
public void handleMessage(Message msg) { ...... switch (msg.what) { case MSG_INVALIDATE: ((View) msg.obj).invalidate(); break; ...... } ...... }
可見其本質就是又在 UI Thread 中呼叫了 View 的 invalidate(),後續便與前面分析過的相同,不再贅述。至此,postInvalidate 分析完成。
依據前面對 invalidate 的分析,我整理出如下流程圖:

依據前面對 postInvalidate 的分析,整理出如下流程圖:

兩者的流程與原理前面已分析完畢,流程圖也已給出,這裡歸納重點如下:
invalidate 系列方法用來請求重繪 View 樹(即 draw 方法)。若 View 大小未變,就不會觸發 layout 過程,而且只繪製那些「需要重繪的」View——哪個 View 呼叫了 invalidate 系列方法,就只繪製該 View(若為 ViewGroup 則繪製整個 ViewGroup)。
常見引起 invalidate 的原因主要有:
直接呼叫 invalidate 方法:請求重新 draw,但只繪製呼叫者本身。 觸發 setSelection 方法:請求重新 draw,但只繪製呼叫者本身。 觸發 setVisibility 方法:當 View 可視狀態由 INVISIBLE 轉為 VISIBLE 時,會間接呼叫 invalidate,進而繪製該 View;當由 INVISIBLE/VISIBLE 轉為 GONE 時,會間接呼叫 requestLayout 與 invalidate,由於 View 樹大小改變,會連帶請求 measure 與 draw,同樣只繪製「需要重新繪製」的視圖。 觸發 setEnabled 方法:請求重新 draw,但不會重新繪製任何 View(含呼叫者本身)。 觸發 requestFocus 方法:請求 View 樹的 draw 過程,只繪製「需要重繪」的 View。分析完 invalidate 後,請回頭想一個問題。本文開頭提到,整個 View 繪製流程最初的程式碼是在 ViewRootImpl 的 performTraversals() 中啟動的,但當時並未說明它究竟是如何被觸發的。現在就來查清這個源頭。
把思路暫且拉回《setContentView 與 LayoutInflater 加載解析機制源碼分析》中對 PhoneWindow 的 setContentView 分析。先看它的源碼:
@Override public void setContentView(View view, ViewGroup.LayoutParams params) { ...... //如果mContentParent為空進行一些初始化,實質mContentParent是通過findViewById(ID_ANDROID_CONTENT);獲取的id為content的FrameLayout的布局 if (mContentParent == null) { installDecor(); } ...... //把我們的view追加到mContentParent mContentParent.addView(view, params); ...... }
這是 Activity 中 setContentView 的實作,再看它呼叫的 addView(即 ViewGroup 的 addView):
public void addView(View child) { addView(child, -1); } public void addView(View child, int index) { ...... addView(child, index, params); } public void addView(View child, int index, LayoutParams params) { ...... //該方法稍後後面會詳細分析 requestLayout(); //重點關注!!! invalidate(true); ...... }
看到 addView 呼叫 invalidate 了嗎?真相就此大白:當我們撰寫一個 Activity 時,必定會透過 setContentView 把要展示的界面傳入,該方法會把我們的界面透過 addView 追加到 id 為 content 的 FrameLayout(ViewGroup)中,而 addView 內部又呼叫 invalidate(true) 去通知觸發 ViewRootImpl 的 performTraversals(),於是便開始遞歸繪製我們自訂的所有布局。
與 invalidate 類似,前面分析繪製流程時也曾呼叫過這個方法,它對 View 同樣重要,因此一併分析。以下是 View 的 requestLayout 源碼:
public void requestLayout() { ...... if (mParent != null && !mParent.isLayoutRequested()) { //由此向ViewParent請求布局 //從這個View開始向上一直requestLayout,最終到達ViewRootImpl的requestLayout mParent.requestLayout(); } ...... }
可見,觸發 View 的 requestLayout,本質上是層層向上傳遞,直到 ViewRootImpl,再觸發它的 requestLayout 方法:
@Override public void requestLayout() { if (!mHandlingLayoutInLayoutRequest) { checkThread(); mLayoutRequested = true; //View調運requestLayout最終層層上傳到ViewRootImpl後最終觸發了該方法 scheduleTraversals(); } }
與前面分析的 invalidate 過程類似,只是設定的標記不同,導致繪製流程中觸發的方法有所差異而已。
這些方法大同小異。就 requestLayout 而言,總結如下:
requestLayout() 會呼叫 measure 與 layout 過程,但不會呼叫 draw 過程,也不會重新繪製任何 View(含呼叫者本身)。
至此,關於 Android 應用開發中的 View 繪製機制及相關重要方法已全部分析完畢。各方法的具體總結這裡不再重複,可直接透過前面的目錄索引,跳至相應方法的總結小節查閱。
Android 應用坐標系統全面詳解
1. 背景 一直有讀者希望我講講自定義控件。網路上這類文章不少,但多數是「授之以魚」——給你一個现成的效果,卻很少系統性地「授之以漁」。而自定義 View 那幾個 onX
Android React Native 自定義組件的完整流程
假設現在有這麼一個需求:自定義一個組件,由一個小圖標和圖標下的文字說明組成,並帶有可設置的背景色、寬度和高度。下圖正是兩個這樣的組件拼成的效果。 第一步:建立組件文件
Android Material Design 元件入門:Toolbar、TabLayout 與 NavigationView
Android Material Design 提供了許多現代化的 UI 元件,例如 Toolbar、TabLayout、AppBarLayout、NavigationV
Android 高效載入大圖片
問題 載入非常大的圖片時,若直接把原始尺寸讀進記憶體,容易造成 OutOfMemoryError。若顯示區域不大,載入過大圖片也不會提升視覺效果,反而浪費資源。 解法