編輯:關於 Android 程式設計
先提一句:當初你選擇繞開的問題,總會在未来的某一天原封不動地回到你面前。所以第一次遇到它的時候,別逃。
很多剛入門的朋友都很好奇一件事——寫在 XML 裡的布局,究竟是經過哪些環節才變成手機螢幕上的畫面?今天我們就從最熟悉的那個方法切入,把 setContentView 的源碼逐段讀一遍。
我們都知道布局是在 onCreate 裡透過 setContentView 載入的,但它內部到底做了什麼?
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
方法體出奇地簡短,只有兩個呼叫。先看第一個:
getWindow().setContentView(layoutResID);
getWindow() 會回傳 mWindow 這個 Window 物件。Window 是抽象類別,用來描述 Activity 最頂端窗口的顯示與行為;既然它是抽象類,setContentView 在這裡自然只是個抽象方法。那麼真正的實作在哪?搜尋 mWindow 的賦值處,答案是:
mWindow = PolicyManager.makeNewWindow(this);
public final class PolicyManager {
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";
private static final IPolicy sPolicy;
static {
// 在執行期把真正的政策實作拉進來
try {
Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
sPolicy = (IPolicy) policyClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);
}
}
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
}
第 38、39 行透過類別路徑 com.android.internal.policy.impl.Policy 動態產生了 sPolicy。順著這條線找到 Policy 類別,裡面寫的是:
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
謎底揭曉:Activity 中的 mWindow,實作類別就是 PhoneWindow。
PhoneWindow 正是抽象類別 Window 的實作,setContentView 的邏輯都在這裡:
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID, getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
開頭先判斷 mContentParent 是否為 null。首次呼叫時條件成立,於是進入 installDecor()。mContentParent 到底是什麼,馬上就會揭曉。
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
// ... 其餘初始化略
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
// ... 標題、背景、轉場動畫等設定略
}
}
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
DecorView 是 PhoneWindow 的內部類別,繼承自 FrameLayout。至此可以確定:setContentView 一開始先造出一個 FrameLayout 家族的外層容器。
mContentParent = generateLayout(mDecor);
把剛才的 DecorView 當參數丟進 generateLayout,回傳值就是 mContentParent。這個方法很長,做的事大致可歸成三類。
第一類:套用主題屬性,初始化視窗特徵。從第 8 行到第 110 行,一路讀取 Window Style 的屬性——是否浮動(mIsFloating,對話框視窗常用)、是否隱藏標題列、是否全螢幕、是否啟用 ActionBar 與其覆疊模式、狀態列與導航列顏色、背景遮罩、視窗進入動畫、輸入法模式等等,全部在這段完成。
第二類:為 DecorView 掛上根布局。第 112 到 187 行依照目前啟用的 feature 挑選一個合適的 screen 配置,透過 LayoutInflater 把它 inflate 成 View,再 addView 進 decor:
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
layoutResource = R.layout.screen_title;
} else {
layoutResource = R.layout.screen_simple;
}
mDecor.startChanging();
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
mContentRoot = (ViewGroup) in;
第三類:找出真正的內容容器並回傳。關鍵在最後這幾行:
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
// ... 背景與標題設定
return contentParent;
也就是說,mContentParent 就是 id 為 android.R.id.content 的那個容器。
以最單純的 R.layout.screen_simple 為例:
<LinearLayout android:fitsSystemWindows="true"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android">
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<FrameLayout android:id="@android:id/content"
android:foreground="?android:attr/windowContentOverlay"
android:foregroundGravity="fill_horizontal|top"
android:layout_height="match_parent"
android:layout_width="match_parent">
</FrameLayout>
</LinearLayout>
結構一目了然:最外層是 LinearLayout,裡頭一個 ViewStub(前面說過,屬性設了才會載入,預設不顯示)與一個 FrameLayout。而這個 FrameLayout 的 id 正是 android:id/content,也就是我們在 generateLayout 最後找到的 mContentParent。
回到 Step 3 那行程式碼:
mLayoutInflater.inflate(layoutResID, mContentParent);
LayoutInflater 把 setContentView 傳進來的布局 id 展開成 View,塞進 mContentParent 這個 FrameLayout 裡。至此,你的 XML 就正式進到 Activity 的視圖樹上了。
把整條流程串起來:
Activity.setContentView
→ Window.setContentView
→ PhoneWindow.setContentView
→ PhoneWindow.installDecor
→ PhoneWindow.generateLayout
→ mLayoutInflater.inflate(layoutResID, mContentParent)
用一句話總結:Activity 內部藏著一個 PhoneWindow,PhoneWindow 裡有個繼承自 FrameLayout 的內部類 DecorView;DecorView 被掛上一層根布局,根布局裡含有一個 id 為 content 的 FrameLayout;而我們在 Activity 中載入的 XML,最後就是被塞進這個 content 裡。

釐清這條鏈路之後,有幾個常見問題自然就有了答案。為什麼 requestWindowFeature(Window.FEATURE_NO_TITLE) 一定要寫在 setContentView 之前?因為 generateLayout 是在 installDecor 階段依當時的 feature 位元決定要挑哪一份 screen 配置,一旦布局已經 inflate 完成,木已成舟。同理,想把整個視窗設成全螢幕,getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN) 也得趕在 setContentView 之前——或者說,至少要趕在 installDecor 實際執行之前,否則只能事後用 hide() 把 ActionBar 藏起來,繞上一圈遠路。
Android Material Design 新控件 TextInputLayout 使用與源碼解析
在 Android L 之前,若想在使用者輸入時即時提示錯誤,通常需要自行監聽輸入事件,再用 Toast 或自訂 View 顯示提示。若處理不好,容易影響體驗。Mater
Android 刪除 Preference 的正確姿势與源碼解析
用 Preference 搭設置界面很省事,一個 XML 就足夠。但想在某個時機動態移除其中一項時,很多人會發現刪不掉——而且往往找不到原因。本文從源碼層面把這件事講清楚
AndroidAnnotations 開發環境配置詳解(Eclipse 版)
過去介紹過 xUtils 這類國內常見的快捷開發框架,但它的註解機制穩定性與可選項目都略嫌不足。AndroidAnnotations 則是國外較早投入註解導向開發的框架,
兩天速成 RecyclerView:從原理到瀑布流與增刪動畫的實戰筆記
RecyclerView 是 Android 5.0 之後推出的全新 View 組件,功能相比 ListView 只強不弱,相信在往後的學習與工作中都會派上用場。這兩天筆