編輯:關於 Android 程式設計
當 Activity 取得焦點時,系統會請求繪製版面配置。這個請求由 Android Framework 處理,繪製從根節點開始,對整棵版面樹進行 measure 與 draw。
整個流程在 ViewRoot.java 的 performTraversals() 函式中展開。這個函式做的事可以概括為三個判斷:是否需要重新計算檢視大小(measure)、是否需要重新安置檢視位置(layout)、是否需要重繪(draw)。

函式呼叫鏈如下:

圖片來源:Arpit Mathur
這裡有個容易搞錯的關鍵:使用者主動呼叫 request,只會觸發 measure 與 layout,不會執行 draw。
從整體來看,這兩個步驟的執行方式如下:

樹的遍歷是有序的:由父檢視到子檢視,每個 ViewGroup 負責測繪它所有的子檢視,而最底層的 View 則負責測繪自身。
measure(int, int) 發起,由上而下有序測量。過程結束時,每個檢視都存好了自己的尺寸與測量規格。layout(int, int, int, int) 發起,同樣自上而下遍歷。每個父檢視依據 measure 得到的尺寸來擺放自己的子檢視。measure 過程會為一個 View 及其所有子節點的 mMeasuredWidth 與 mMeasuredHeight 賦值,可透過 getMeasuredWidth() 與 getMeasuredHeight() 取得。這兩個值必須落在父檢視約束的範圍內,才能確保所有父檢視都接收得到子檢視的測量結果。
如果子檢視對 measure 出來的大小不滿意,父檢視會介入並設定測量規則進行第二次 measure。例如父檢視可以先以未指定的 dimension 測量每個子檢視,若最終發現子檢視的未約束尺寸太大或太小,就換一個確切大小再測一次。這也是 onMeasure() 有可能被呼叫多次的原因。
這是我們最常見的類別,用來指定檢視的高與寬。對於每個檢視的 height 與 width,有三種選擇:
100dp每個 ViewGroup 子類都有對應的 LayoutParams 子類,例如 RelativeLayout 對應 RelativeLayout.LayoutParams。呼叫 view.getLayoutParams() 得到的其實就是其所在父檢視類型的 LayoutParams——若 View 的父容器是 RelativeLayout,那麼得到的就是 RelativeLayout.LayoutParams。搞錯這點,強轉時就會噴 ClassCastException。
測量規格,包含「測量要求」與「尺寸」兩部分資訊,由 32 位元整數打包而成(高 2 位存模式,低 30 位存尺寸)。共三種模式:
match_parent 或具體數值。父容器可用 MeasureSpec.getSize(measureSpec) 直接取得尺寸。wrap_content。這種模式下父容器無法確定子 View 的尺寸,只能由子檢視自行計算——這正是自訂檢視必須實作測量邏輯的場景。measure(int widthMeasureSpec, int heightMeasureSpec)View.java 中,為 final 修飾,不可覆寫。但它最終會回呼 View / ViewGroup 的 onMeasure(),所以自訂檢視時只要覆寫 onMeasure() 即可。onMeasure(int widthMeasureSpec, int heightMeasureSpec)setMeasuredDimension()onMeasure() 中呼叫,把計算結果傳入,測量階段即結束。這是必須呼叫的方法,否則會拋出 IllegalStateException。自訂檢視時不必理會系統複雜的測量過程,只要呼叫它設定依 MeasureSpec 算出的尺寸即可,可以參考 ViewPagerIndicator 的 onMeasure 實作。下圖是 measureChildren(int widthMeasureSpec, int heightMeasureSpec) 的呼叫流程:

/**
* 請求所有子 View 去 measure 自己。
* 需要考量的部分:對子 View 的測繪要求 MeasureSpec,以及自身的 padding。
* 這裡會跳過所有 GONE 狀態的子 View。
* 最繁重的工作在 getChildMeasureSpec 中處理。
*/
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);
}
/**
* measureChildren 中最繁重的部分:為每個 ChildView 算出自己的 MeasureSpec。
* 目標是把 ChildView 的 MeasureSpec 與 LayoutParams 結合,得到最合適的結果。
*/
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
// ... 依據子檢視的測量要求與大小建立 MeasureSpec
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
/** measure 為 final,最終一定回呼 onMeasure */
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
// ...
onMeasure(widthMeasureSpec, heightMeasureSpec);
// ...
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
首先要明確:子檢視的具體位置都是相對於父檢視而言的。
View 的 onLayout 是空實作,而 ViewGroup 的 onLayout 是 abstract 的。因此自訂的 View 若繼承 ViewGroup,就必須實作 onLayout。
layout 過程中,子檢視會呼叫 getMeasuredWidth() 與 getMeasuredHeight() 取得 measure 階段的結果作為自身寬高,然後呼叫每個子檢視的 layout(l, t, r, b) 來確定它在父檢視中的位置。
@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);
}
}
/** 遍歷所有子 View,為其設定相對父檢視的座標 */
void layoutVertical(int left, int top, int right, int bottom) {
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(); // measure 階段確定的寬
final int childHeight = child.getMeasuredHeight(); // measure 階段確定的高
// ... 計算 childLeft、childTop
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
}
}
}
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
// View.java
public void layout(int l, int t, int r, int b) {
// ...
setFrame(l, t, r, b);
}
/** 為該子 View 設定相對其父檢視的座標 */
protected boolean setFrame(int left, int top, int right, int bottom) {
// ...
}
View.draw(Canvas canvas)onDraw(Canvas)。若確實需要覆寫,請先呼叫 super.draw(canvas) 完成系統繪製,再做自訂處理。View.onDraw()dispatchDraw()繪製流程圖:

/**
* Manually render this view (and all of its children) to the given Canvas.
* The view must have already done a full layout before this function is called.
*
* When implementing a view, implement onDraw(android.graphics.Canvas)
* instead of overriding this method. If you do need to override this method,
* call the superclass version.
*/
public void draw(Canvas canvas) {
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background if needed
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children (dispatchDraw)
* 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)
final int viewFlags = mViewFlags;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
return;
}
// Step 2, save the canvas' layers ...
// 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
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
}
從這段程式碼可以直接讀出一個效能優化技巧:當不需要繪製 Layer 時,第二步與第五步會被整段跳過。因此繪製時能省掉的 layer 就盡量省,可以明顯提升效率。
dispatchDraw(Canvas canvas) {
// ...
if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
// 處理 ChildView 的動畫
final boolean buildCache = !isHardwareAccelerated();
for (int i = 0; i < childrenCount; i++) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
final LayoutParams params = child.getLayoutParams();
attachLayoutAnimationParameters(child, params, i, childrenCount);
bindLayoutAnimation(child);
if (cache) {
child.setDrawingCacheEnabled(true);
if (buildCache) {
child.buildDrawingCache(true);
}
}
}
}
final LayoutAnimationController controller = mLayoutAnimationController;
if (controller.willOverlap()) {
mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
}
controller.start();
}
// 繪製 ChildView —— 只繪製 VISIBLE 狀態的檢視
for (int i = 0; i < childrenCount; i++) {
int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null) {
more |= drawChild(canvas, child, drawingTime);
}
}
// ...
}
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
drawChild(canvas, this, drawingTime)child.draw(canvas, this, drawingTime)。文件明確說明:除了被 ViewGroup.drawChild() 呼叫外,你不應該在其他任何地方覆寫或調用該方法。而 View.draw(Canvas) 才是自訂檢視中可以覆寫的方法。從參數可以看到 child.draw(canvas, this, drawingTime) 處理了與父檢視相關的邏輯,但最終的繪製仍落在 View.draw(Canvas)。invalidate()layout(),且只會繪製那些呼叫了 invalidate() 的 View。requestLayout()measure() 與 layout(),但不會進行 draw。ViewRoot.performTraversals() 統一決策。onMeasure() 中算出尺寸並呼叫 setMeasuredDimension()。onLayout()。onDraw(),ViewGroup 不要覆寫 dispatchDraw()。invalidate() 只重繪,requestLayout() 只重測與重排——搞混這兩個,是效能問題的常見來源。
Android 內容觀察者實戰:監聽簡訊資料庫變化
當我們需要即時掌握 Android 系統中某個資料庫的變化,例如簡訊收件匣的更新,就可以使用內容觀察者 ContentObserver。它能夠在指定 URI 的內容發生改
Android 自定義 Dialog 實例詳解
自訂 Dialog 常用於顯示條款、提醒、確認視窗或需要使用者選擇的情境。透過自訂版面與樣式,可以讓 Dialog 更符合產品設計。 實作重點 可建立繼承 Dialog
Android 動態佈局實作:在執行期動態加入 TextView 與 ListView
本文以一個完整實例說明如何在 Android 中透過程式碼動態配置介面,重點示範執行期動態加入 TextView 與 ListView 的做法,供需要的朋友參考。核心思路
Android 仿支付寶支付密碼輸入框實作
支付密碼輸入框的視覺重點支付密碼框通常不會直接顯示數字,而是以圓點表示已輸入位數。為了貼近常見支付 App 的體驗,可以自訂 EditText,在 onDraw 中畫出外