LayoutInflate.inflate(...)深入源码分析

作者: Fizzer | 来源:发表于2016-08-12 15:09 被阅读379次

    先上个图:


    LayoutInflate.inflate(...)

    上图是LayoutInflate.inflate(...)的每个重载的方法中参数的类型,方法也不是很多,我们就一个个来看看他源码是怎么样子的。

    那么我们先把这几个参数是做什么用的解释了,以便后面方法的理解:

    • int resource:布局文件xml的资源id
    • ViewGroup root:如果attchToRoot为true的话,root作为父布局
    • XmlPullParser parser:Android自带的xml解析类型,产生DOM节点
    • boolean attachToRoot:是否加载到root布局中

    源码分析:

    可以从红色框框看到调用的是第一张图片中第三个重载方法:

    inflate(resource, root)

    那么我们去看看那个调用的方法又是如何实现的:

    inflate(resource, root, attachToRoot)

    从上图代码中,我么可以看到,其将传入的xml布局解析成XmlResourceParser格式后,调用了第一张图片的第四个重载方法。在这里,根据第一个方法的return,我们可以推测下,第二个方法是不是也是调用了第四个重载方法呢?现在就看源码验证!

    inflate(parser, root)

    果然验证了我们的猜想,那么我们就来看看第四个重载方法,看看他的奥秘在哪里,先上源码:

    /**
      * Inflate a new view hierarchy from the specified XML node. Throws
      * {@link InflateException} if there is an error.
      * <p>
      * <em><strong>Important</strong></em>   For performance
      * reasons, view inflation relies heavily on pre-processing of XML files
      * that is done at build time. Therefore, it is not currently possible to
      * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
      *
      * @param parser XML dom node containing the description of the view  
      *        hierarchy.
      * @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.)
      * @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.
      * @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.
      */
    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("<merge /> 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) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (Exception 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;
            }
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            return result;
        }
    }
    
    判断最外层是否是merge

    可知道,当根节点是merge的时候,只能是在root != null && attachToRoot = true的时候,否者会报异常。

    对父布局root判断

    红色框中,返回的是xml布局的LayoutParams参数大小。该方法是调用ViewGroup中方法来实例化获得LayoutParams数据。所以就是说,当没有传递root进来的时候。就不能获得xml布局中的大小参数。而接着当attachToRoot为false的时候,将params赋给temp。

    LayoutInflate.png

    从上面代码我们知道,当 root != null && attachToRoot为true的时候,将temp添加到root布局中返回(这里return的是result,但在方法的一开始有将root赋给result,这里root与result其实就是等价的了)。而当root == null || attachToRoot为false的时候,将temp赋给result返回。说明,当root == null 的时候,attachToRoot设置true/false都是没关系的。

    对了。连注释都忘了解释:

    方法注释转译

    最后总结:

    • 若root = null,则attachToRoot无所谓true/false,并不能获得任何效果,那么xml中最外层的布局的layout_width和layout_height设置将失效。
    • 若root != null && attachToRoot = false,不加载到root中,使得Layout文件中(最常用的例子就是adapter中的layout)最外层的布局的layout_width和layout_height设置将有效。
    • 若root != null && attachToRoot = true,加载到root中,并将root返回。

    以上是个人学习观点,若有不恰当或不正确的地方,欢迎指正。一起学习。

    hierarchy n. 层级;等级制度

    相关文章

      网友评论

        本文标题:LayoutInflate.inflate(...)深入源码分析

        本文链接:https://www.haomeiwen.com/subject/itldsttx.html