美文网首页
布局加载LayoutInflater使用

布局加载LayoutInflater使用

作者: MacroZH | 来源:发表于2018-05-14 21:28 被阅读0次

LayoutInflater用来加载xml等布局资源文件,通过解析这些布局资源文件返回一个View(布局文件中定义的根View)。

1 取得LayoutInflater实例

获得LayoutInflater有两种方法:

//context 是上下文对象,如Activity,Service等
LayoutInflater inflater=LayoutInflater.from(context);
LayoutInflater inflater=(LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);

View 对象中提供一个静态的inflate方法 View.inflate(),内部使用的也是LayoutInflater

    /**
     * Inflate a view from an XML resource.  This convenience method wraps the {@link
     * LayoutInflater} class, which provides a full range of options for view inflation.
     *
     * @param context The Context object for your activity or application.
     * @param resource The resource ID to inflate
     * @param root A view group that will be the parent.  Used to properly inflate the
     * layout_* parameters.
     * @see LayoutInflater
     */
    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

2 使用inflate()方法

通过实例对象的inflate()方法来加载布局文件,常用的有两种重载方法

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

第一个参数为对应xml资源的id号,第二个参数为ViewGroup对象,如果需要指定View之间的相对关系的话,这个对象就是加载后View的父View,第三个参数是boolean类型的参数,用来指定是否将加载的View作为root的子View,当第二个参数不为null的时候第三个参数才有意义。

2.1 加载一个独立的布局View

如果只是单独加载一个布局,不建立与root的父子关系的话有两种方式(root为null或者root不为null,且attachToRoot=false),这两者的区别就在于如果如果root不为null时候在xml文件中定义的控件布局属性将会得到保留,当这个View被添加到一个父布局的时候这些属性就会生效,否则xml中定义的属性也就无效。

//root 为null
View view=inflater.inflate(R.layout.XXX,null);
//root 不为null
View view=inflater.inflate(R.layout.xxx,root,false);

注: 加载后的view还没有经过测量、布局、绘制的过程,此时的View还没有宽和高,通过getMeasureHeight()等方法取得的值为0

2.2 加载一个布局View并且作为root的子View

指定root,并且设置attachToRoot=true时候,加载的布局就会作为一个子View挂载在root下面。

//不设置第三个参数,root不为null时候默认attachToParent=true
View view=inflater.inflate(R.layout.xxx,root);
View view=inflater.inflate(R.layout.xxx,root,true);

**注: 作为子View的形式加载布局,返回的View是父布局,也就是root对象,如果使用attachToRoot=false则返回加载的View,因此inflate()方法返回的是加载过程中涉及到的View中最上层的那个View **

3 inflate()方法的工作过程

首先来看下三个参数的重载方法inflate(R.layout.id,root,attachToParent)的源码

    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();
        }
    }

首先通过xml资源文件来实例化一个XmlResourceParser对象parser。之后继续调用重载方法。parser对象是用来解析xml文件的,是android中提供的pull方式进行解析,通过这个对象可以提取DOM树中对应的节点信息与节点的属性信息。

final XmlResourceParser parser = res.getLayout(resource);
//传入parser对象的重载方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

在这个重载方法中就是通过这个parser对象来对XML文件中定义的各个View以及属性来进行解析转化成为对应的View对象与属性等。
来看一下这个重载方法,这里只列出部分主流程代码,其他的代码省略显示。

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
                   .
                   .
                   .
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            //result是最终返回的View
            View result = root;
            try {
                   .
                   .
                   .
                if (TAG_MERGE.equals(name))
                {
                    .
                    .
                    .
                    //递归搜寻xml树实例化对应的View
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else
                 {
                    // temp 是xml文件搜索到的最上层的View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //如果root!=null 此时xml文件中定义的属性有效,这里生成LayoutParams来记录这些属性
                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                           //如果attachToRoot=false,这里讲params设置给temp,当temp被添加到其他ViewGroup时候这些params就会生效
                            temp.setLayoutParams(params);
                        }
                    }
                    //循环加载temp下面所有的View
                    rInflateChildren(parser, temp, attrs, true);
                    //root不为空,且第三个参数attachToRoot=true 加载的View作为root子View,调用addView()方法
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                    //root==null 或者 attachToRoot=false 这时候加载的View作为独立的View不和root建立关系,此时设置result=temp
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {
                   .
                   .
                   .
            }
            return result;
        }
    }

最开始解析属性得到AttributeSet对象attrs,然后定义了一个View对象result=root,注意这个result就是方法最后返回的View。从最后面两个if判断可以看到,如果root != null && attachToRoot,则temp添加到root中作为子View,如果 root == null || !attachToRoot 则讲temp设置给result,之后返回的就是这个temp。

final View temp = createViewFromTag(root, name, inflaterContext, attrs);

通过这句方法可以看出这个temp应该就是xml文件中定义的最顶层的那个View。

再看一下最外层的if

    if (TAG_MERGE.equals(name))
    {
                    .
                    .
                    .
                    //递归搜寻xml树实例化对应的View
       rInflate(parser, root, inflaterContext, attrs, false);
     } else{
                    .
                    .
                    .
     }

判断条件是TAG_MERGE,也就是XML文件中定义的最外层使用merge标签,此时attachToParent只能设置成true,否则会抛出异常,merge中定义的子View也是会添加到root下成为root的子View。

相关文章

网友评论

      本文标题:布局加载LayoutInflater使用

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