編輯:關於 Android 程式設計
上一篇我們探討了 Activity 的啟動,從 startActivity() 到進程創建,再到 Activity 的創建,最後調用 onCreate() 方法。本篇我們接著 onCreate() 繼續深入研究 Activity 加載 layout 的過程。
我們寫好 layout 佈局後,在 onCreate() 中調用 setContentView(layoutID) 就能把佈局加載並顯示出來。這一過程究竟做了什麼?佈局中的控件又是怎樣被加載並呈現的?我們就從 setContentView() 開始一步步剖析(參考源碼版本為 API 23)。
通常我們會在 onCreate() 中設置佈局資源 ID。Activity 提供了三個設置視圖的方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// setContentView(new TextView(this));
// setContentView(new TextView(this), new ViewGroup.LayoutParams(...));
}
再看 Activity 中的調用關係:
public class Activity ... {
private Window mWindow;
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public void setContentView(View view) {
getWindow().setContentView(view);
initWindowDecorActionBar();
}
public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initWindowDecorActionBar();
}
final void attach(...) {
// 初始化 mWindow
mWindow = new PhoneWindow(this);
...
}
public Window getWindow() {
return mWindow;
}
}
原來,Activity 中的 setContentView() 最終調用的是 PhoneWindow 對象 mWindow 的 setContentView() 方法。而 mWindow 是在 Activity 創建時於 attach() 方法中初始化的。
每一個 Activity 組件都有一個關聯的 Window 實現類 PhoneWindow 的對象 mWindow,用來描述一個應用程序窗口。它封裝了頂層窗口的外觀與行為策略,提供了標准的用戶界面策略,如背景、標題區域、默認按鍵處理等。PhoneWindow 管理整個屏幕的內容(不含屏幕最頂部的系統狀態欄),因此它與應用的某一個頁面相關聯。
@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 {
// 將資源文件通過 LayoutInflater 轉換為 View 樹,並添加至 mContentParent
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
setContentView(view) 接著調用 setContentView(view, layoutParams),而後者與 setContentView(layoutResID) 的步驟大同小異,唯一區別是:前者把傳入的 view 直接 add 到 mContentParent,而後者透過 mLayoutInflater.inflate() 把佈局填充進 mContentParent。
由此可見,我們為某個 Activity 寫的 layout 視圖,最終都被添加到了一個叫 mContentParent 的 ViewGroup 中。在加入之前,若 mContentParent 為 null,會先執行 installDecor() 進行初始化;若已初始化且窗口非透明,則清空其中的所有視圖。由於 mContentParent 只會實例化一次,所以多次調用 setContentView() 只是替換了它的子視圖(也就是我們寫的佈局文件)。
我們猜測 installDecor() 的作用是實例化 mContentParent,下面深入 PhoneWindow 驗證:
// id 為 content 的容器,用於盛放我們寫的 layout 視圖
private ViewGroup mContentParent;
// mContentRoot 是整個界面內容,包括 title 和 content 等
private ViewGroup mContentRoot;
// 窗口頂層 FrameLayout,用於盛放 mContentRoot
private DecorView mDecor;
private void installDecor() {
if (mDecor == null) {
// ①. 初始化窗口
mDecor = generateDecor();
...
}
if (mContentParent == null) {
// ②. 初始化根布局
mContentParent = generateLayout(mDecor);
...
}
}
DecorView 是 FrameLayout 的子類,也就是我們常聽說的 Activity 頂層窗口 mDecor。installDecor() 中,第①步判斷 mDecor 是否為 null,若為 null 則調用 generateDecor() 實例化一個 DecorView;第②步判斷 mContentParent 是否為 null,若為 null 則調用 generateLayout(mDecor) 進行初始化。
protected ViewGroup generateLayout(DecorView decor) {
// ①. 獲取 AndroidManifest.xml 中指定的 themes 主題
TypedArray a = getWindowStyle();
// 根據主題設置窗口是否有標題、是否全屏等屬性
...
// ②. 根據窗口屬性 Features 選擇相應的修飾佈局文件
int layoutResource;
int features = getLocalFeatures();
...
// ③. 將選定的佈局文件 inflate 為 View 樹
View in = mLayoutInflater.inflate(layoutResource, null);
// ④. 將整個窗口內容添加到根 mDecor 中
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// ⑤. 將整個窗口內容賦值給 mContentRoot
mContentRoot = (ViewGroup) in;
// ⑥. 找到 id 為 "@android:id/content" 的 View 賦值給 mContentParent
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
...
return contentParent;
}
第①步透過 getWindowStyle() 獲取當前 Window 在 theme 中定義的屬性(窗口支持的屬性可參考 frameworks/base/core/res/res/values/attrs.xml 中的 <declare-styleable name="Window">),並調用 setFlags()、requestFeature() 設置全屏、標題等屬性。這也解釋了為什麼我們通常在 onCreate() 中設置全屏等屬性時,必須放在 setContentView() 之前——因為此後 installDecor() 已經執行完畢,再設置就無效了。
確定 layoutResource 後,第③步用 mLayoutInflater 解析出對應的視圖 in,第④步將其 add 到 mDecor,第⑤步賦值給 mContentRoot,第⑥步透過 findViewById() 找到 id 為 content 的 View 賦值給 mContentParent。
由此,我們發現三個重要的視圖對象:mDecor、mContentRoot、mContentParent。它們的關係是:mDecor 嵌套 mContentRoot,mContentRoot 嵌套 mContentParent。所以在第⑥步能直接調用 findViewById() 找到 mContentParent。
關係圖如下:

頂層窗口 mDecor 與容器 mContentParent 初始化完畢後,接下來就是把我們的佈局添加到 mContentParent 中。回到 setContentView(layoutResID),其核心是這一句:
mLayoutInflater.inflate(layoutResID, mContentParent);
其中 hasFeature(FEATURE_CONTENT_TRANSITIONS) 是 Android 5.0 引入的屬性,用於判斷窗口內容變化是否需要動畫。我們主要研究 View 的加載過程,故不深入動畫,直接看 inflate():
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
這個方法有兩個關鍵參數:root 是解析 layout 後所得視圖層級的父視圖;attachToRoot 決定是否將解析出的視圖添加到父視圖。由於 inflate(resource, root) 傳入的 attachToRoot 為 root != null,所以最終返回的是已將佈局添加進 mContentParent 後的 mContentParent。
接著它把 layout 關聯到一個 XmlResourceParser(Android 內建的 pull 解析器),再調用 inflate(parser, root, attachToRoot):
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
View result = root;
// ②. 循環直到解析到開始標簽
while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {}
// ③. 找到第一個開始標簽,name 即整個 layout 最外層的父控件
final String name = parser.getName();
...
// ④. 根據 name 創建 View 對象 temp(即 xml 中的根控件)
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
...
// ⑤. 遞歸解析 temp 中的所有子控件
rInflateChildren(parser, temp, attrs, true);
// ⑥. 若 root 不為空,將 view 樹添加到 root 中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
...
return result;
}
可見真正完成 inflate 的並非這個方法本身,它只解析了最外層控件,剩餘子控件是由 rInflateChildren() 遞歸完成的,而其內部調用的是 rInflate()。
createViewFromTag() 根據控件名實例化控件對象。關鍵邏輯是:先判斷 name 中是否含有 '.' 字符——若沒有,則視為 Android 自帶 View,會在 name 前加上包名前綴;若有,則視為自定義 View,直接按全名創建。
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
rInflate() 負責解析最外層 parent 中的所有子控件。它是一個遞歸方法,layout 中有多少個 ViewGroup,就會遞歸調用多少次。
void rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate) {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 遞歸解析 view 中的子控件
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
值得注意的是,當 parent 的所有子控件都 inflate 完畢後會調用 onFinishInflate()。這個方法在自定義 ViewGroup 時經常用到——因為在構造方法中並未完成子控件的實例化,所以只能等到 onFinishInflate() 回調中再用 findViewById 初始化子控件。
本篇分析了 View 的加載填充原理,也就是從調用 setContentView() 開始,我們的佈局如何被填充為整棵 View 樹並掛載到 Activity 上。重點知識點如下:
1、每個 Activity 都有一個關聯的 PhoneWindow 對象 mWindow,它管理整個屏幕內容(不含系統狀態欄),封裝了頂層窗口的外觀與行為策略。
2、Activity 的 setContentView() 內部調用的是 PhoneWindow 的 setContentView()。
3、PhoneWindow 引用了 mDecor(頂層窗口,FrameLayout 子類)、mContentRoot(整個 Activity 內容,含 Title、ActionBar 等)、mContentParent(mContentRoot 中 id 為 content 的容器,用於放置我們的 layout)。三者關係為 mDecor 嵌套 mContentRoot,mContentRoot 嵌套 mContentParent。
4、若 mContentParent 為 null,說明是首次調用,需透過 installDecor() → generateLayout() 完成頂層窗體 View 樹的搭建。
5、setContentView(layoutId) 最後調用 LayoutInflater.inflate() 把 layout 填充為 View 樹:inflate() 只解析最外層父控件,內部子控件由 rInflateChildren() 遞歸完成,遇到開始標簽時調用 createViewFromTag() 實例化 View 並解析屬性。
6、inflate() 執行完畢後,layout 被映射為 View 樹並 add 到 mContentParent,整個 Activity 的 View 樹就此形成。
Android Activity 四大啟動模式實驗詳解
Activity 是 Android 四大元件之一,也是使用者最直接接觸的介面。不同啟動模式會影響 Activity 的實例建立、堆疊管理與返回行為。本文透過實驗方式說明
用 Lambda 表達式取代 Android 中的匿名內部類
Lambda 是希臘字母表的第十一碼(大寫 Λ、小寫 λ)——嗯,跑題了。回到正題:Lambda 表達式是 Java 8 的招牌新特性之一,同批登場的還有: Lambd
Android 插件化開發入門:從 Java 反射到動態加載
關於 Android 的插件化其實已經討論很久了,但市面上還缺少非常成熟靠譜的插件框架。本文嘗試對比一下在 Java 中使用插件化的流程,並探討如何將其移植到 Andro
線性表數據結構(五):哈希表與 HashMap 源碼深度解讀
在之前的文章里,我分析过数组和链表两种线性表结构。数组存储区间连续、查找方便,但插入删除效率低;链表存储区间离散、插入删除方便,但查找困难。那么有没有一种结构既能快速查找