博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LayoutInflater源码解析
阅读量:6905 次
发布时间:2019-06-27

本文共 9373 字,大约阅读时间需要 31 分钟。

hot3.png

我们经常实用的LayoutInflater这样用:

View view = LayoutInflater.from(context).inflate(R.layout.resource,root,flase);

进入inflate进行源码解析

public View inflate(@LayoutRes int resource, [@Nullable](https://my.oschina.net/u/2896689) 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为后面解析xml文件做准备

继续进入inflate(为方便阅读删除一些调试代码和异常捕获代码,只保留了核心代码)

public View inflate(XmlPullParser parser, [@Nullable](https://my.oschina.net/u/2896689) ViewGroup root, boolean attachToRoot) {    synchronized (mConstructorArgs) {        final Context inflaterContext = mContext;        final AttributeSet attrs = Xml.asAttributeSet(parser);        Context lastContext = (Context) mConstructorArgs[0];        mConstructorArgs[0] = inflaterContext;        View result = root;        try {            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) { // 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); } } rInflateChildren(parser, temp, attrs, true); // 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) {...}

`

这段源码中看出主要逻辑为:

1、判断xml局中标签是否为merge,如果是则走rInflate直接去遍历创建xml所有的View对象

2、进入非merge的逻辑里面,会创建根View,主要的过程在createViewFromTag创建View

3、rInflateChildren创建子View

3、接下来如果传入的root不为null,并且attachToRoot==false,则对创建好的View的ViewGroup.LayoutParams是通过generateLayoutParams生成的。

4、如果root不为null,attachToRoot==true,那么则将整个View作为一个子View加入到父布局中,否则直接返回这个View

继续进入createViewFromTag源码(为方便理解去除异常彩蛋和ignoreThemeAttr属性的代码) `

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,        boolean ignoreThemeAttr) {    if (name.equals("view")) {        name = attrs.getAttributeValue(null, "class");    }    try {        View view;        if (mFactory2 != null) {            view = mFactory2.onCreateView(parent, name, context, attrs);        } else if (mFactory != null) {            view = mFactory.onCreateView(name, context, attrs);        } else {            view = null;        }        if (view == null && mPrivateFactory != null) {            view = mPrivateFactory.onCreateView(parent, name, context, attrs);        }        if (view == null) {            final Object lastContext = mConstructorArgs[0];            mConstructorArgs[0] = context;            try {                if (-1 == name.indexOf('.')) {                    view = onCreateView(parent, name, attrs);                } else {                    view = createView(name, null, attrs);                }            } finally {                mConstructorArgs[0] = lastContext;            }        }		……

这段源码中看出主要逻辑为:

1、标签为view时获取view的class属性作为要创建的View的name(注意View和view的区别)

2、主要通过不同的Factory通过**createView() **去创建View

3、其中有个逻辑需要在onCreateView执行之前判断是否存在“.”,存在点则表示不是系统的View,需要单独处理,在后面createView的代码可以看到有这样一段加入了“android.view.”,后面会讲这句的用途。

protected View onCreateView(String name, AttributeSet attrs)        throws ClassNotFoundException {    return createView(name, "android.view.", attrs);}

继续进入onCreateView源码

public final View createView(String name, String prefix, AttributeSet attrs)        throws ClassNotFoundException, InflateException {    Constructor
constructor = sConstructorMap.get(name); if (constructor != null && !verifyClassLoader(constructor)) { constructor = null; sConstructorMap.remove(name); } Class
clazz = null; try { if (constructor == null) { // Class not found in the cache, see if it's real, and try to add it clazz = mContext.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); if (mFilter != null && clazz != null) { boolean allowed = mFilter.onLoadClass(clazz); if (!allowed) { failNotAllowed(name, prefix, attrs); } } constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); sConstructorMap.put(name, constructor); } else { // If we have a filter, apply it to cached constructor if (mFilter != null) { // Have we seen this name before? Boolean allowedState = mFilterMap.get(name); if (allowedState == null) { // New class -- remember whether it is allowed clazz = mContext.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); boolean allowed = clazz != null && mFilter.onLoadClass(clazz); mFilterMap.put(name, allowed); if (!allowed) { failNotAllowed(name, prefix, attrs); } } else if (allowedState.equals(Boolean.FALSE)) { failNotAllowed(name, prefix, attrs); } } } Object lastContext = mConstructorArgs[0]; if (mConstructorArgs[0] == null) { // Fill in the context if not already within inflation. mConstructorArgs[0] = mContext; } Object[] args = mConstructorArgs; args[1] = attrs; final View view = constructor.newInstance(args); if (view instanceof ViewStub) { // Use the same context when inflating ViewStub later. final ViewStub viewStub = (ViewStub) view; viewStub.setLayoutInflater(cloneInContext((Context) args[0])); } mConstructorArgs[0] = lastContext; return view; }

这段源码虽然很复杂,但主要做的事就是 通过反射的方式去加载一个View类

这段代码就能解释上面为什么要加“android.view.”,这段代码会将系统的View的路径拼起来,把类加载进来;

clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubclass(View.class)

到现在,我们讲完了对于xml根view的创建逻辑,还有个很重要的流程没有讲:

子View创建 的逻辑在inflate中的rInflateChildren

进入rInflateChildren,这里依然会进入到rInflate()

void rInflate(XmlPullParser parser, View parent, Context context,        AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {    final int depth = parser.getDepth();    int type;    boolean pendingRequestFocus = false;    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)) {            pendingRequestFocus = true;            consumeChildElements(parser);        } else if (TAG_TAG.equals(name)) {            parseViewTag(parser, parent, attrs);        } else if (TAG_INCLUDE.equals(name)) {            if (parser.getDepth() == 0) {                throw new InflateException("
cannot be the root element"); } parseInclude(parser, context, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException("
must be the root element"); } 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 (pendingRequestFocus) { parent.restoreDefaultFocus(); } if (finishInflate) { parent.onFinishInflate(); }}

这段源码的大致可以总结为:

1、总的逻辑为获取xml文档的层级数,解析每一层级的数据

2、解析过程首先进行View的合理性校验,include、merge等标签;

3、最后还是会走到createViewFromTag 创建出 View 对象,如果是 ViewGroup则递归调用rInflateChildren

到这里基本上所有的流程讲完了,这里总结一下加载流程:

**1、拿到Xml解析对象,为后续解析做准备

2、对整个Xml中的布局控制处理由 root、attachToRoot这两个参数控制

3、解析子View,通过createViewFromTag创建实例对象**

转载于:https://my.oschina.net/617669559/blog/3015380

你可能感兴趣的文章
Vijos P1596 加法表【迭代】
查看>>
整体二分笔记
查看>>
css学习_文本有关的样式属性、sublime快捷生成标签
查看>>
Mysql学习
查看>>
jsp页面无法获取controler层model值解决方案
查看>>
[C++] Swap Two Num
查看>>
详解ABBYY FineReader 12扫描亮度设置
查看>>
线程同步利与弊,线程同步的前提
查看>>
js的escape()、encodeURI()、encodeURIComponent()区别详解
查看>>
python2与python3的区别
查看>>
HDU2196-Computer
查看>>
cpp
查看>>
nginx 报错502Bad Gateway
查看>>
决定转移ubuntu
查看>>
Linux下查看文件内容时去掉空行和#开头的注释行
查看>>
[转载]linux 查看当前用户id、whoami用户列表、用户组、用户权限/etc/p
查看>>
Python简易购物车程序
查看>>
mui 关闭除指定页面之外的其他所有页面.
查看>>
反向引用 /1, /2...
查看>>
STM32配置一般过程(持续更新中)
查看>>