編輯:關於 Android 程式設計
Activity 是四大組件中最常見的一個,onCreate() 裡的 setContentView() 更是每個人都寫過無數次。但很少有人真正追問:這個布局 ID 是怎麼變成屏幕上可見的視圖層級的?DecorView、PhoneWindow、mContentParent 之間到底是什麼關係?
本文就沿着源碼把這條鏈路走一遍。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
Activity 自己什麼都沒做,只是把活轉給了 Window。而 getWindow() 返回的是成員變量 mWindow:
public Window getWindow() {
return mWindow;
}
mWindow 在哪裡被實例化?答案是 Activity 的 attach() 方法——它在 Activity 啟動流程中就被調用,此時 mWindow 被賦值為 PhoneWindow:
final void attach(Context context, ActivityThread aThread, Instrumentation instr,
IBinder token, int ident, Application application, Intent intent,
ActivityInfo info, CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
attachBaseContext(context);
mFragments.attachHost(null /* parent */);
mWindow = new PhoneWindow(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
// ... 後續賦值 mUiThread、mMainThread、mToken 等
}
也就是說,getWindow().setContentView(layoutResID) 本質上就是 PhoneWindow.setContentView(layoutResID)。
public abstract class Window { ... }
public class PhoneWindow extends Window { ... }
private final class DecorView extends FrameLayout { ... }
PhoneWindow 是一個隱藏類,需要下載 Android SDK Source 查看,路徑為 sdk/source/android-x/com/android/internal/policy/impl/PhoneWindow.java。
@Override
public void setContentView(int layoutResID) {
// 注意:FEATURE_CONTENT_TRANSITIONS 可能在 installDecor 過程中才被設置
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();
}
}
可以看到兩條分支:開啟了內容切換動畫的走 Scene 轉場,否則直接 inflate 進 mContentParent。而 hasFeature() 的判斷依賴 mFeatures:
public boolean hasFeature(int feature) {
return (getFeatures() & (1 << feature)) != 0;
}
protected final int getFeatures() {
return mFeatures;
}
默認情況下 mFeatures 中並未打開 FEATURE_CONTENT_TRANSITIONS,所以首次調用時 mContentParent 為 null,會先執行 installDecor();後續再次調用則會先清空 mContentParent 的所有子 View,再把新的布局 inflate 進去——這也解釋了為什麼在 Activity 中反覆調用 setContentView 不會層層疊加。
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent =
(DecorContentParent) mDecor.findViewById(R.id.decor_content_parent);
if (decorContentParent != null) {
mDecorContentParent = decorContentParent;
mDecorContentParent.setWindowCallback(getCallback());
if (mDecorContentParent.getTitle() == null) {
mDecorContentParent.setWindowTitle(mTitle);
}
// ...
}
}
}
這個方法做了兩件事:創建 DecorView,再通過 generateLayout() 生成 mContentParent。
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
generateDecor() 樸素得令人意外——就是 new 一個 DecorView 實例。
這個方法很長,核心邏輯是「讀取主題屬性 → 決定窗口特性 → 選擇對應的系統布局 → 從中取出 content 容器」。
protected ViewGroup generateLayout(DecorView decor) {
// 讀取當前主題的窗口樣式
TypedArray a = getWindowStyle();
mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR) & (~getForcedWindowFlags());
if (mIsFloating) {
setLayout(WRAP_CONTENT, WRAP_CONTENT);
setFlags(0, flagsToUpdate);
} else {
setFlags(FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
}
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
} else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
requestFeature(FEATURE_ACTION_BAR);
// ...
}
// ...
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_title_icons;
}
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = a.getResourceId(
R.styleable.Window_windowActionBarFullscreenDecorLayout,
R.layout.screen_action_bar);
} else {
layoutResource = R.layout.screen_title;
}
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = R.layout.screen_simple_overlay_action_mode;
} 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;
// 從骨架中取出 id 為 content 的容器
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
mDecor.finishChanging();
return contentParent;
}
拆開看,這個方法實際上分成三段:
第一段(mDecor.startChanging() 之前):讀取主題屬性,判斷窗口是否浮動、是否需要標題欄、是否有 ActionBar,據此決定 requestFeature 的組合。這些代碼看起來瑣碎,但本質上是在「配置窗口外觀」。
第二段:根據 features 的位運算結果選擇一個系統預置的骨架布局。可以看到候選名單很清楚——screen_swipe_dismiss、screen_title_icons、screen_action_bar、screen_title、screen_simple_overlay_action_mode,最終兜底是 screen_simple。這一步就是「為不同風格的窗口挑選不同的根布局文件」。
第三段:把選中的骨架 inflate 出來,addView 到 DecorView 上作為根視圖,然後通過 findViewById(ID_ANDROID_CONTENT) 取出其中 id 為 content 的容器——通常是一個 FrameLayout,最後把它返回。
這個 R.id.content 大家或多或少都聽說過,它正是接下來所有 Activity 布局的落腳點。
現在 mContentParent 已經就緒,回到 PhoneWindow.setContentView() 的最後一行:
mLayoutInflater.inflate(layoutResID, mContentParent);
就這一句。我們傳入的 activity_home.xml 被 inflate 成一棵 View 樹,掛到 id 為 content 的 FrameLayout 之下。至此,布局正式進入視圖層級。
把上面的分析串成一條線:
整個層級結構因此是:DecorView(含 TitleBar/ActionBar)→ content(FrameLayout)→ 我們的 activity_home.xml 根節點。
理解它並不只是滿足好奇心,有幾個很實際的用途:
findViewById(android.R.id.content) 比硬編碼自己的根布局 id 更可靠。
[Android 測試] 深入 MonkeyRunner:性能回歸測試、插件擴展與批處理整合
一、MonkeyRunner 簡介 MonkeyRunner 是 Android SDK 自帶的一款開源測試工具,位於 sdk/tools 目錄下。它主要用於性能測試與回
Android 圓角圓形圖片(一):使用 Xfermode 實作圓角與圓形 ImageView
實作目標本篇要建立一個可顯示圓形或圓角的 ImageView,並保留一般圖片檢視的基本行為。Xfermode 概念PorterDuff.Mode 可用來控制圖層合成方式。
RecyclerView 下拉刷新與加載更多:一次講透封裝思路與踩坑記錄
「下拉刷新 + 上滑加載更多」幾乎是資訊類應用的標配交互。聽起來簡單,真正動手時卻要同時應對 RecyclerView、SwipeRefreshLayout、滑動監聽、
Android Context 與 Application:全局對象的數據共享實踐
Interface to global information about an application environment. This is an abstrac