源码分析-setContentView都做了些什么
一直以来只是盲目的写代码,然后教程上入门时候也是告诉你这么做就OK了,有很多东西都不知道为什么,最近正好搞了份6.0的源码,所以就试着来分析下之前感觉迷茫的点,本次要探究我们在Activity的Oncreate方法里面调用setContentView都做了些什么
- 开始之前先说下本次用到的工具以及源码获取方式,本次主要用到的工具Source Insight
- 源码获取方式:
1、自己搞个Linux虚拟机然后下载,这个自己可以去搜索相关教程
2、福利(需要翻墙),当然我下载了是Android6.0的FrameWork层的代码,如果你要烧录的话,请参考1
Activity
Activity.java的位置framework\base\core\java\android\app
这里左边栏搜索setContentView方法可以看到有三个重载的方法,如下图
这个三个方法的代码结构是这样子的,相对源码略有修改
public void setContentView(params params...) {
//调用Window的方法
getWindow().setContentView(params);
//初始化ActionBar
initWindowDecorActionBar();
}
PhoneWindow
追查发现Activity内部持有的是一个private Window mWindow;
所以我们接下来要搜索这个Window(位置framework\base\core\java\android\view)追查进去发现这个Window是个抽象类,那么我们久要找他的实现类PhoneWindow,接下来我们就可以查看这个PhoneWindow的setContentView的方法
public void setContentView(int layoutResID) {
...
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
...
} else {
//这里填充布局
mLayoutInflater.inflate(layoutResID, mContentParent);
}
...
}
mContentParent
这里可以查看mContentParent的声明
// This is the view in which the window contents are placed. It is either
// mDecor itself, or a child of mDecor where the contents go.
private ViewGroup mContentParent;
意思大概是这个ViewGroup就是顶层的Decor或者他包含的要加载的子View(英文比较烂,英文好的童鞋可以自行理解)
LayoutInflater
这段代码做了一些列的判断然后调用了LayoutInflater的inflate方法,继续追查LayoutInflater.java位于 framework\base\core\java\android\view目录下,查看inflate方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
//首先获取Xml布局中书写的资源
final XmlResourceParser parser = res.getLayout(resource);
try {
//这里做了填充
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
上面这段代码可以看到主要是两个方法
- res.getlayout用于获取我们在xml中声明的标签
-
inflate(parser,root,attchToRoot)用于填充布局
首先我们先看res.getLayout(resource)这个方法主要用于加载清单文件中的一系列标签体,有兴趣可以另行查看,inflate的代码如下,一下代码我尽量保留英文注释方便英文水平比较好的同学查看
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
...
View result = root;
try {
// Look for the root node.找寻根节点
...
final String name = parser.;();
...
if (TAG_MERGE.equals(name)) {
//如果是merge标签走这里
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
//temp就是xml文件中的根节点
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied
//找到根节点的layoutparams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
//讲layoutparams交给根节点的View
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context.
//遍历跟节点temp所包涵的子View添加到temp中
rInflateChildren(parser, temp, attrs, true);
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
// root不为空,直接将根节点View添加到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.
// root等于null,直接返回根节点temp
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (Exception e) {
...
} finally {
// Don't retain static reference on context.
//释放资源
...
}
return result;
}
}
上面这段代码主要有两个方法需要注意
- rInflateChildren(parser, temp, attrs, true)
-
createViewFromTag(root, name, inflaterContext, attrs)
先看createViewFromTag的代码
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
...
try {
View view;
...
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
return view;
}catch (Exception e) {
...
}
}
LayoutInflater#createView()
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
return onCreateView(name, attrs);
}
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
new HashMap<String, Constructor<? extends View>>();
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//缓存过的View的构造方法
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
//如果没有缓存该View的构造方法
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
...
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
//如果有缓存的构造方法那就使用缓存的
...
}
//实例化出View
final View view = constructor.newInstance(args);
//ViewStub的懒加载...
...
return view;
}catch (Exception e) {
...
}
}
上面可以看到无论走那个分支最终都是会执行createView的,那么这里面用一个HashMap来存储已经解析过的View,如果没有解析过这个View,那么就直接反射获取该View的构造方法new出来一个实例,这里也可以看出为什么要避免频繁的inflate操作
LayoutInflater#rInflateChildren
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
void rInflate(XmlPullParser parser, View parent, Context context,
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)) {
} else if (TAG_TAG.equals(name)) {
} else if (TAG_INCLUDE.equals(name)) {
} else if (TAG_MERGE.equals(name)) {
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
上面代码可以看出,循环遍历每个节点的tag,如果是特殊节点如include、merge那就不去解析View,如果是ImageView、LinearLayout等View的子类那么我就去调用createViewFromTag实例化这个View然后添加到根节点去,之后再递归调用rInflateChildren去填充下一层级的ViewGroup,如此反复直至所有的View都已经实例化并且添加完毕到这里我们就分析完setContentView到底做了些什么,第一次写源代码分析有些生疏,大家见谅
网友评论