View 绘制体系知识梳理(1) LayoutInflater#inflate 源码解析

前几天在经过LayoutInflater渲染出子布局,并添加进入父容器的时候,出现了子布局的宽高属性不生效的状况,为此,总结一下和LayoutInflater相关的知识。java

1、得到LayoutInflater

Android当中,若是想要得到LayoutInflater实例,一共有如下3种方法:node

1.1 LayoutInflater inflater = getLayoutInflater();

这种在Activity里面使用,它实际上是调用了android

/**
     * Convenience for calling
     * {@link android.view.Window#getLayoutInflater}.
     */
    @NonNull
    public LayoutInflater getLayoutInflater() {
        return getWindow().getLayoutInflater();
    }
复制代码

下面咱们再来看一下Window的实现类PhoneWindow.javabash

public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
    }
复制代码

它其实就是在构造函数中调用了下面1.2的方法。 而若是是调用了Fragment中也有和其同名的方法,可是是隐藏的,它的理由是:dom

/**
     * @hide Hack so that DialogFragment can make its Dialog before creating
     * its views, and the view construction can use the dialog's context for * inflation. Maybe this should become a public API. Note sure. */ public LayoutInflater getLayoutInflater(Bundle savedInstanceState) { final LayoutInflater result = mHost.onGetLayoutInflater(); if (mHost.onUseFragmentManagerInflaterFactory()) { getChildFragmentManager(); // Init if needed; use raw implementation below. result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory()); } return result; } 复制代码

1.2 LayoutInflater inflater = LayoutInflater.from(this);

public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }
复制代码

能够看到,它实际上是调用了1.3,可是加上了判空处理,也就是说咱们从1.1当中的Activity1.2方法中获取的LayoutInflater不可能为空。ide

1.3 LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

这三种实现,默认最终都是调用了最后一种方式。函数

2、LayoutInflater#inflate

inflater一共有四个重载方法,最终都是调用了最后一种实现。布局

2.1 (@LayoutRes int resource, @Nullable ViewGroup root)

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     * 
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
复制代码

该方法,接收两个参数,一个是须要加载的xml文件的id,一个是该xml须要添加的布局,根据root的状况,返回值分为两种:性能

  • 若是root == null,那么返回这个root
  • 若是root != null,那么返回传入xml的根View

2.2 (XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

/**
     * 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.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }
复制代码

它的返回值状况和2.1相似,不过它提供的是否是xmlid,而是XmlPullParser,可是因为View的渲染依赖于xml在编译时的预处理,所以,这个方法并不合适。ui

2.3 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     * 
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @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(@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();
        }
    }
复制代码

若是咱们须要渲染的xmlid类型的,那么会先把它解析为XmlResourceParser,而后调用2.4的方法。

2.4 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

/**
     * 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) {
            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;
            try {.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                //1.若是根节点的元素不是START_TAG,那么抛出异常。
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
                final String name = parser.getName();
                //2.若是根节点的标签是<merge>,那么必需要提供一个root,而且该root要被做为xml的父容器。
                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");
                    }
                    //2.1递归地调用它全部的孩子.
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    //temp表示传入的xml的根View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //若是提供了root而且不须要把xml的布局加入到其中,那么仅仅须要给它设置参数就好。
                    //若是提供了root而且须要加入,那么不会设置参数,而是调用addView方法。
                    if (root != null) {
                        //若是提供了root,那么产生参数。
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    //递归地遍历孩子.
                    rInflateChildren(parser, temp, attrs, true);
                    if (root != null && attachToRoot) {
                        //addView时须要加上前面产生的参数。
                        root.addView(temp, params);
                    }
                    //若是没有提供root,或者即便提供root可是不用将root做为parent,那么返回的是渲染的xml,在`root != null && attachToRoot`时,才会返回root。
                    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; } return result; } } 复制代码

咱们简单总结一下英文注释当中的说明,具体的流程能够看上面的中文注释。

  • 做用:从特定的xml节点渲染出一个新的view层级。
  • 提示:为了性能考虑,不该当在运行时使用XmlPullParser来渲染布局。
  • 参数parser:包含有描述xml布局层级的parser xml dom
  • 参数root,能够是渲染的xmlparentattachToRoot == true),或者仅仅是为了给渲染的xml层级提供LayoutParams
  • 参数attachToRoot:渲染的View层级是否被添加到root中,若是不是,那么仅仅为xml的根布局生成正确的LayoutParams
  • 返回值:若是attachToRoot为真,那么返回root,不然返回渲染的xml的根布局。

3、不指定root的状况

由前面的分析可知,当咱们没有传入root的时候,LayoutInflater不会调用temp.setLayoutParams(params),也就是像以前我遇到问题时的使用方式同样:

LinearLayout linearLayout = (LinearLayout) mLayoutInflater.inflate(R.layout.linear_layout, null);
mContentGroup.addView(linearLayout);
复制代码

当没有调用上面的方法时,linearLayout内部的mLayoutParams参数是没有被赋值的,下面咱们再来看一下,经过这个返回的temp参数,把它经过不带参数的addView方法添加进去,会发生什么。 调用addView后,若是没有指定index,那么会把index设为-1,按前面的分析,那么下面这段逻辑中的getLayoutParams()必然是返回空的。

public void addView(View child, int index) {
        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }
        LayoutParams params = child.getLayoutParams();
        if (params == null) {
            params = generateDefaultLayoutParams();
            if (params == null) {
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
            }
        }
        addView(child, index, params);
    }
复制代码

在此状况下,为它提供了默认的参数,那么,这个默认的参数是什么呢?

protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
复制代码

也就是说,当咱们经过上面的方法获得一个View树以后,将它添加到某个布局中,这个View数所指定的根布局中的宽高属性实际上是不生效的,而是变为了LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT

相关文章
相关标签/搜索