继续 Activity 相关的源码阅读。

打开 Activity 的 setContentView(int layoutResID) 方法:

1
2
3
4
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initActionBar();
}

先来看 getWindow() 方法,发现实际上是直接返回了一个 Window 抽象类,查找后发现,mWindow 是在 attach 方法中初始化的,而前一篇博客(Activity 的启动过程分析{:target=”_blank”})中末尾讲解到, Activity 最终会在 ActivityThread.performLaunchActivity() 中调用 onCreate 等方法,开始进入 Activity 的生命周期,而在调用 onCreate 之前,则会先调用 attach 方法,完成 Window 等成员的初始化工作。
1
2
3
4
5
6
7
8
9
10
11
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) {
attachBaseContext(context);
mFragments.attachActivity(this);
// 初始化 mWindow
mWindow = PolicyManager.makeNewWindow(this);
}

打开 PolicyManager 类,可以发现,mWindow 实际上是由 IPolicy 接口的某一个实现类所创建,PolicyManager 顶部可以发现:
1
2
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";

因此,直接打开 Policy.makeNewWindow(Context context) 即可查看到实际上是返回的是 new PhoneWindow(context),花这些时间来查看 Window 的创建,实际上是要查看 Window.setContentView(int resLayoutID) 的具体实现方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
// 初始化 mDector 和 mContentParent
installDecor();
} else {
mContentParent.removeAllViews();
}
//
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}

有时间的话,可以查看 installDector() 方法,可以发现 Dector 实际上是继承自 FrameLayout ,这也是为什么 Activity 的布局最顶层是 FrameLayout 的原因。
接着查看 mLayoutInflater.inflate() 方法,直接跟进实际调用的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// 查找根节点
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
}

final String name = parser.getName();

// 解析 <merge /> 标签
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}

rInflate(parser, root, attrs, false);
} else {
// Temp is the root view that was found in the xml
View temp;
if (TAG_1995.equals(name)) {
temp = new BlinkLayout(mContext, attrs);
} else {
// 根据 Tag 创建 View
temp = createViewFromTag(root, name, attrs);
}

ViewGroup.LayoutParams params = null;

if (root != null) {
// 解析 rootView 属性
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
// Inflate 子节点控件
rInflate(parser, temp, attrs, true);
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
// 将解析的数据添加进 root 中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
return result;
}
}

接着看一下是如何通过 createViewFromTag() 创建 View 的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
View createViewFromTag(View parent, String name, AttributeSet attrs) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}

try {
View view;
// 会调用 PhoneLayoutInflater.onCreateVew(),进而调用 LayoutInflater.createView()
if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
else view = null;

if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
}

if (view == null) {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
}

if (DEBUG) System.out.println("Created view is: " + view);
return view;

} catch (InflateException e) {
throw e;

} catch (ClassNotFoundException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;

} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}

直接查看 LayoutInflater.createView() 方法可以发现,实际上是通过 ClassLoader 来加载类并生成实例对象。
回到 inflate 方法,加载子控件也是使用的此方法,有兴趣的可以自行查看。