总结一下代码解析xml文件生成View对象。
常用的有两种解析方法
(1) View.inflate(context, resource, root)
(2) inflater.inflate(resource, root, attachToRoot)
其中第一个方法也是调用的第二个方法
/**
*
* @param resource ID for an XML layout resource to load (e.g.,<code>R.layout.main_page</code>)
资源id
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
如果attachToRoot 为true,root会成为生成层级父容器,如果是false,就会给生成的view提供一个LayoutParams对象。
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
如果是false,root仅仅创建一个LayoutParams对象为生成的层级结构(view 对象),
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
attachToRoot是true。返回root View,root为父容器,解析出的xml view 添加到root中。否则返回xml文件生成的view
*/
官方的注释其实很明白了
resource 就是你想要的xml文件
root 父容器
attachToRoot 是否是添加到root 父容器中。
如果root 为null,attachToRoot 没有效果
如果root不为null,attachToRoot 是true,返回的view 是root,生成的xml view 以child view的形式添加到root 中。
如果root不为null,attachToRoot 是false,返回的view是解析xml文件生成的view,该view 的父布局参数是通过root view生成的,
源码逻辑
View result = root;
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// 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);
}
}
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;
}