編輯:關於 Android 程式設計
很多人寫了兩三年 Android,卻說不清「一個 View 是怎麼出現在屏幕上的」。要回答這個問題,得先認識兩個關鍵角色:ViewRoot 與 DecorView。
ViewRoot 在源碼中對應的實現類是 ViewRootImpl,它是 WindowManager 與 DecorView 之間的紐帶。當 ActivityThread 完成 Activity 對象的創建之後,會把 DecorView 添加到 Window 中,同時創建一個 ViewRootImpl 對象,並讓它與 DecorView 建立關聯。可以這樣理解:DecorView 是「要畫什麼」,ViewRootImpl 是「什麼時候畫、怎麼畫」。
整個繪製流程從 ViewRoot.performTraversals() 開始,依次經過 measure、layout、draw 三個階段,最終把 View 呈現在屏幕上:
另外,DecorView 是所有界面的「頂級 View」。我們調用 setContentView 時,自己寫的布局其實是被添加到了一個 id 為 content 的 FrameLayout 中,因此可以通過下面的方式把它取出來:
ViewGroup content = (ViewGroup) findViewById(android.R.id.content); View view = content.getChildAt(0);
MeasureSpec 是一個 32 位的 int 值:高 2 位是 SpecMode(測量模式),低 30 位是 SpecSize(該模式下的規格大小)。之所以用一個 int 同時裝兩份信息,是為了在傳遞過程中省內存。
SpecMode 共有三類:
match_parent 和具體數值。wrap_content。對於 DecorView,它的 MeasureSpec 由窗口尺寸與自身的 LayoutParams 共同決定:
MATCH_PARENT:精確模式,大小等於窗口大小;WRAP_CONTENT:最大模式,大小不確定,但不能超過窗口大小;對於普通 View,規則稍微複雜一些,由父容器的 MeasureSpec 與自身的 LayoutParams 共同決定:
match_parent 時:父容器是 EXACTLY 則子 View 也是 EXACTLY(取父容器剩餘空間);父容器是 AT_MOST 則子 View 也是 AT_MOST(不超過父容器剩餘空間)。wrap_content 時:無論父容器是 EXACTLY 還是 AT_MOST,子 View 一律是 AT_MOST,且不能超過父容器剩餘空間。MeasureSpec 一旦確定,onMeasure 裡就能算出測量寬高了。
View 的 measure() 被聲明為 final,子類無法重寫,但它內部一定會調用 onMeasure()——這才是我們自定義控件時應該覆寫的方法。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
核心邏輯都在 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;
}
也就是說,在 AT_MOST 與 EXACTLY 兩種常見情況下,返回值就是 specSize。而 View 的最終大小是在 layout 階段確定的,絕大多數場景下測量大小與最終大小一致。
UNSPECIFIED 的情況比較特殊,View 的尺寸取自 getSuggestedMinimumWidth() 與 getSuggestedMinimumHeight():
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth
: max(mMinWidth, mBackground.getMinimumWidth());
}
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
總結一下:若 View 沒有設置背景,返回 android:minWidth 指定的值(未指定則為 0);若設置了背景,則返回 android:minWidth 與背景固有寬度中的較大值。
實戰結論:自定義控件時一定要處理 wrap_content 的情況,否則在布局裡寫 wrap_content,效果等同於 match_parent。
ViewGroup 除了測量自己,還要遍歷調用所有子元素的 measure,形成遞歸。它提供了一個通用方法:
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);
}
ViewGroup 本身是抽象類,並不規定具體的測量策略——不同布局特性要由子類自己實現。以 LinearLayout 為例:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
豎直方向下,系統會遍歷子元素並逐一調用 measureChildBeforeLayout()(內部仍然走 child.measure),同時用 mTotalLength 累計初步高度,累加的內容包括子元素高度與其在豎直方向上的 margin:
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
final int usedHeight = totalWeight == 0 ? mTotalLength : 0;
measureChildBeforeLayout(child, i, widthMeasureSpec, 0, heightMeasureSpec, usedHeight);
mTotalLength = Math.max(mTotalLength,
mTotalLength + childHeight + lp.topMargin + lp.bottomMargin
+ getNextLocationOffset(child));
}
所有子元素測完,再來測量自己:
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = Math.max(mTotalLength, getSuggestedMinimumHeight());
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
setMeasuredDimension(
resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState);
可見:若 LinearLayout 高度寫的是 match_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:
result = (specSize < size) ? (specSize | MEASURED_STATE_TOO_SMALL) : size;
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}
極端情況下系統可能多次 measure 才能定下最終尺寸,因此想拿準確寬高,最好放到 onLayout 中獲取。
方案一:onWindowFocusChanged。View 初始化完成後即可獲取,但該回調在獲得與失去焦點時都會觸發,會被調用多次。
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
}
方案二:view.post(Runnable)。post 會把任務投遞到消息隊列尾部,等 Looper 執行到它時,View 早已完成初始化。
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override public void run() {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
方案三:ViewTreeObserver。註冊 OnGlobalLayoutListener,View 樹狀態變化時會被回調(記得及時移除監聽)。
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
方案四:手動 measure。需要依 LayoutParams 分情況處理:
match_parent:無法得知父容器剩餘空間,測不出結果;wrap_content:用 AT_MOST,並以 View 理論最大值作為上限。int widthMeasureSpec = MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); view.measure(widthMeasureSpec, heightMeasureSpec);
int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, View.MeasureSpec.AT_MOST); int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, View.MeasureSpec.AT_MOST); view.measure(widthMeasureSpec, heightMeasureSpec);
這裡的 (1 << 30) - 1 並非隨手一寫:SpecSize 只用低 30 位存儲,最大值正是 30 個 1,用理論上限去構造 AT_MOST 是合理的做法。
layout 的作用是確定 View 在父容器中的位置。ViewGroup 位置確定後,會在 onLayout 中遍歷所有子元素並調用其 layout 方法,而 layout 內部又會回調 onLayout,層層遞進。
public void layout(int l, int t, int r, int b) {
int oldL = mLeft, oldT = mTop, oldB = mBottom, 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;
// 通知 OnLayoutChangeListener ...
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
先由 setFrame 設定四個頂點,mLeft / mTop / mRight / mBottom 一確定,View 的位置就定了;接著調用 onLayout 讓父容器去擺放子元素。以 LinearLayout 的豎直布局為例:
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.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
childTop += lp.topMargin;
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
}
}
}
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
傳入的 width / height 正是子元素的測量寬高,於是一次 layout 就完成了整棵 View 樹的定位。
public final int getWidth() { return mRight - mLeft; }
public final int getHeight() { return mBottom - mTop; }
getWidth / getHeight 取自 layout 階段賦值的四個頂點,因此返回的是最終寬高;而 getMeasuredWidth / getMeasuredHeight 來自 measure 階段。兩者賦值時機不同,默認實現下通常相等,但並非必然。比如:
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.layout(l, t, r + 100, b + 100);
}
這段代碼會讓 View 的最終寬高永遠比測量寬高大 100px。另一種情況是需要多次 measure 才能定型的 View,前幾輪的測量值與最終值可能不同——但最終仍會收斂一致。
draw 的職責是把 View 真正畫到屏幕上,流程固定為六步:
background.draw(canvas)onDraw()dispatchDraw()onDrawForeground()public void draw(Canvas canvas) {
// Step 1, draw the background, if needed
if (!dirtyOpaque) {
drawBackground(canvas);
}
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
}
子元素的繪製由 dispatchDraw 遍歷完成,draw 事件就這樣一層層傳遞下去。這裡還有一個容易被忽略的優化開關:
public void setWillNotDraw(boolean willNotDraw) {
setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
}
View 默認不開啟該標記,但 ViewGroup 默認開啟。所以當你自定義的 ViewGroup 確實需要通過 onDraw 繪製內容時,必須顯式調用 setWillNotDraw(false),否則你寫的 onDraw 永遠不會被執行——這是新手最常踩的坑之一。
onDetachedFromWindow() 是很好的時機(Activity 退出或 View 被 remove 時觸發);相對的 onAttachedToWindow() 則在 View 重新附加時回調。View 變得不可見時也應停止線程與動畫。把 measure、layout、draw 這三條主線理清楚,再回頭看源碼,大多數「詭異的顯示問題」都能找到答案。
TableView 懸浮按鈕實作:兩種讓按鈕不隨滾動的方案
直接把 Button 貼在 TableViewController 上,按鈕會跟著列表一起滾走。要讓它固定在畫面上,有兩種常見解法:一是把 tableView 當普通子
Android 常用布局解析:線性、幀、表格與相對布局
為什麼要使用 XML 描述布局Android 常用 XML 來宣告介面布局,讓畫面呈現與程式邏輯分離。這樣不僅方便修改樣式,也能降低後續維護成本。開發者也可以透過視覺化工
Android Adapter 使用教學(中):用 SimpleAdapter 打造圖文並茂的 ListView
前面幾篇談的是 ArrayAdapter。用它在 ListView 裡擺純文字確實夠用,但實 projects 裡我們往往還想放圖片——這就是 SimpleAdapter
用 Zipalign 優化 APK:adb 與 Root Explorer 兩種實機操作法
打包完成的 APK 最好再做一次優化。原因很簡單:APK 的本質就是一個 zip 壓縮檔,經過對齊處理之後,包內未壓縮的資料會整齊排列,能有效降低應用程式執行時的記憶體消