我们都知道 MVC,在Android中,这个 V 即指View,那我们今天就来探探View的究竟。

在onCreate方法中,可以调用this.setContentView(layout_id),来设置这个Activity的视图,今天就从setContentView(…)说起吧。

先编写一个简单的Activity:

1
2
3
4
5
6
7
8
public class ViewDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.view_demo);
}
}

查看父类Activity的setContentView方法:

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

这个getWindow()指向哪里?我们在onCreate中打个log瞧瞧:

1
D/ViewDemoActivity(3969): com.android.internal.policy.impl.PhoneWindow

原来是PhoneWindow,来看看它的setContentView方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public void setContentView(int layoutResID) {
// 1
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
// 2
mLayoutInflater.inflate(layoutResID, mContentParent);
// 3
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}

我们分三步来介绍这个方法:

第一步:判断父容器是否为空

为空:生成Decor; (Decor是什么?参看这篇文章)
不为空:删除 contentParent 所有的子控件。

第二步:解析layoutResID所代表的xml文件

直接看LayoutInflater.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// 为节省篇幅,删除一些调试代码
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
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 {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
// 根标签为merge时,root不能为空
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 {
temp = createViewFromTag(root, name, attrs);
}
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied
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);
}
}
// 解析temp的所有子View
rInflate(parser, temp, attrs, true);
// 将temp添加到root中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果未指定root或者不附加到root,则返回xml所代表的view;
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;
}
}

(这几个inflate方法内部的逻辑,请参看注释)
我们注意到,inflate(…)最终会调用rInflate(…),继续挖:

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
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
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_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else if (TAG_1995.equals(name)) {
final View view = new BlinkLayout(mContext, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
} else {
final View view = createViewFromTag(parent, name, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) parent.onFinishInflate();
}

rInflate(…)先特殊处理了几个xml标签mergeincludeblinkrequestFocus
然后在else分支,会 递归 调用rInflate(…),将xml的子控件添加到parent中,生成完整的 contentView
看了这里,同学们就会明白,为什么不建议在布局文件中做过多地View嵌套了吧,层层递归啊:(

第三步:通知Callback,ContentView发生改变

这个getCallback()是什么?打个Log看看:

1
2
3
4
5
6
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.view_demo);
Log.d("ViewDemo", getWindow().getCallback().toString());
}

输出结果为:

1
D/ViewDemoActivity( 7228): cn.erhu.android.view.ViewDemoActivity@6562f2c0

这不就是ViewDemoActivity吗?
在Activity.java中,我们在attach()方法中发现了蛛丝马迹:

1
2
3
4
5
6
7
8
final void attach(...) {
...
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
...
}
public void onContentChanged() {
}

我们发现原来PhoneWindow的callback原来就是Activity,并且Activity的onContentChanged()方法是空的,所以我们可以在自己的Activity中重写这个方法,来监听ContentView发生改变的事件。

OK,setContentView()大体就是这么回事,下面再补充几个知识点。


补充知识点

1、PhoneWindows的mLayoutInflater是哪里来的?

PhoneWindow.java

1
2
3
4
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}

LayoutInflater.java

1
2
3
4
5
6
7
8
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}

ContextImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Override
public Object getSystemService(String name) {
ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
return fetcher == null ? null : fetcher.getService(this);
}
private static void registerService(String serviceName, ServiceFetcher fetcher) {
if (!(fetcher instanceof StaticServiceFetcher)) {
fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
}
SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
}
static {
...
registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) {
return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
}});
...
}

原来,mLayoutInflater是ContextImpl.java在加载的时候,调用PolicyManager.makeNewLayoutInflater生成的

PoliceManager.java

1
2
3
4
5
6
7
8
9
10
11
12
13
private static final String POLICY_IMPL_CLASS_NAME = "com.android.internal.policy.impl.Policy";
private static final IPolicy sPolicy;
static {
// Pull in the actual implementation of the policy at run-time
try {
Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
sPolicy = (IPolicy)policyClass.newInstance();
...
}
public static LayoutInflater makeNewLayoutInflater(Context context) {
return sPolicy.makeNewLayoutInflater(context);
}

最终定位到Policy.java

1
2
3
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}

mLayoutInflater是一个PhoneLayoutInflater,这便是mInflaterLayout的由来。