Layinflater
概述
LayoutInflater这个类相信大家都不陌生,当我们平时需要加载layout文件来转换成View的场景都会用到它,其中最常用的有如下两个加载方法:View inflate(int resource, ViewGroup root)
View inflate(int resource, ViewGroup root, boolean attachToRoot)
可能一直在使用,却并未了解其中参数真正的奥义所在,让我们从源码中看下这几个参数究竟代表着什么。
源码分析
先看下两个参数的inflate,源码如下:public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null);
}
可以看到,其实它内部还是调用了三个参数的inflate,且只有root不为null时,attachToRoot这个参数才会传true。那我们可以直接看三个参数的inflate:public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { final Resources res = getContext().getResources(); if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
} final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
首先获取资源对象然后将其转换为XmlResourceParser对象,XmlResourceParser对象可以解析layout.xml文件中的具体属性和标签等信息,那就进而看inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)这个方法:public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate"); final Context inflaterContext = mContext; final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
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(); if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
} if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException(" can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else { // Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
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 (DEBUG) {
System.out.println("-----> start inflating children");
} // Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true); if (DEBUG) {
System.out.println("-----> done inflating children");
} // We are supposed to attach all the views we found (int temp)
// to root. Do that now.
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) { final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE); throw ie;
} catch (Exception e) { final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE); throw ie;
} finally { // Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
} return result;
}
}
我们一步步来看,首先是读取START_TAG,这个代表着xml文件里的根标签,如果读不到,说明没有设置好根部标签,抛出No start tag found!的异常,接着判断根标签是否为merge标签,如果是的话,attachToRoot必须为true且root不能为null,这也就是为什么如果你要加载的layout文件中根布局是merge就必须设置父布局的原因。
接着会读取我们的layout文件,将其中的根布局读出来转换为View对象(即源码中的temp),然后判断root是否为null,假如root不为空,则会调用root的layoutparams,并且设置给temp,如果root不为空并且attachRoot也为true时,就会调用addView(),将temp的layoutparams设置给它自己,然后再将root作为最终结果传出去,如果root为null或者attachRoot为false,则将temp返回出去(此时的temp还是一开始初始化的我们layout文件的根布局View)。
通俗一点讲就是如下三种情况:如果root为null或者attachToRoot为false时,则调用layout.xml中的根布局的属性并且将其作为一个View对象返回。
如果root不为null,但attachToRoot为false时,则先将layout.xml中的根布局转换为一个View对象,再调用传进来的root的布局属性设置给这个View,然后将它返回。
如果root不为null,且attachToRoot为true时,则先将layout.xml中的根布局转换为一个View对象,再将它add给root,最终再把root返回出去。(两个参数的inflate如果root不为null也是相当于这种情况)
验证
源码分析完了,总得举个栗子验证一下,先创建一个简单的自定义View继承于LinearLayout如下:/**
* Created by YANG on 2019/2/22.
*/public class ViewGroupTestView extends LinearLayout{ public ViewGroupTestView(Context context) { this(context, null);
} public ViewGroupTestView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0);
} public ViewGroupTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);
View view = LayoutInflater.from(context).inflate(R.layout.layout_view_group, null);
Log.d("Android小Y", view.getClass().getName());
}
}
layout_view_group.xml最外层用一个RelativeLayout包裹,如下:<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
日志打印如下:02-16 02:47:34.267 24091-24091/com.example.test.main D/Android小Y: android.widget.RelativeLayout
可以看到为root传的是null,也就是默认导致attachToRoot也为false,这个时候就使用layout_view_group.xml中的根布局(即RelativeLayout)返回。
接着我们把参数改一下,改为如下:View view = LayoutInflater.from(context).inflate(R.layout.layout_view_group, this, false);
可以看到将我们的LinearLayout作为root传进去,但attachToRoot为false,这个时候打印出来依然类型是RelativeLayout。
如果在此基础上把attachToRoot设为true:View view = LayoutInflater.from(context).inflate(R.layout.layout_view_group, this, true);
结果如下:02-16 03:02:15.630 24634-24634/? D/Android小Y: com.example.test.main.ViewGroupTestView
可以看到这次不是RelativeLayout了,而是我们传进去的自定义View对象,那按我们刚才的猜想,这个对象的第一个子View是不是应该就是RelativeLayout呢,测试一下:View view = LayoutInflater.from(context).inflate(R.layout.layout_view_group, this, true);
ViewGroupTestView testView = (ViewGroupTestView) view;
Log.d("Android小Y", testView.getChildAt(0).getClass().getName());
日志如下:02-16 03:07:21.805 24923-24923/com.example.test.main D/Android小Y: android.widget.RelativeLayout
果不其然,我们将第一个子View打印出来,正是RelativeLayout,说明已经被添加进去了。
总结
说了这么多,总结一下个人对这几个参数的理解吧。
三个参数时,root的参数是否为空,决定了我们要不要沿用root的布局属性,attachToRoot是否为true,决定了是否将我们的layout作为子View添加进去。
两个参数时,root既决定了是否要沿用root的布局属性,也决定了是否要将我们的layout作为子View添加进去。
返回值:一旦root为空或者attachToRoot为false,返回值为xml的根View,其它情况都会返回root
作者:Android小Y
链接:https://www.jianshu.com/p/3f871d95489c