天天看点

LayoutInflater源码简析

关于LayoutInflater的基本用法就不再累述了,本篇主要通过分析inflate()的源码搞清几个参数的作用。

首先来看一个Demo,这个Demo很简单就是通过调用LayoutInflater的inflate方法获取一个蓝色背景的TextView并以match_parent的形式添加到一个300dp*100dp的RelativeLayout上,我们传递不同的参数来看一下实现效果之间的差别。

先来看一下这两个布局文件

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_blue_dark"
          android:gravity="center"
          android:text="Hello World"
          android:textColor="#fff"
          android:textSize="18sp">

</TextView>
           
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/content"
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:orientation="vertical">

    </RelativeLayout>

    <TextView
        android:id="@+id/params"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:textColor="#555"
        android:textSize="14sp"/>

</LinearLayout>
           

再来看一下实现代码和对应的实现效果,同时我们输出TextView的宽和高。

No.1

View textView = LayoutInflater.from(this).inflate(R.layout.textview, null);
content.addView(textView);
           
LayoutInflater源码简析

No.2

LayoutInflater源码简析

No.3

View textView = LayoutInflater.from(this).inflate(R.layout.textview, content, false);
content.addView(textView);
           
LayoutInflater源码简析

可以看到只有第二和第三种方式实现了我们想要的效果,为什么第一种不可以呢?根据输出的TextView的宽和高我们应该能猜出一些端倪。那就是通过第二,第三种方式得到的TextView设置了宽高都为match_parent的LayoutParams,为什么会这样呢,让我们通过源码一探究竟。

注:

/**
         * Special value for the height or width requested by a View.
         * MATCH_PARENT means that the view wants to be as big as its parent,
         * minus the parent's padding, if any. Introduced in API Level 8.
         */
        public static final int MATCH_PARENT = -;

        /**
         * Special value for the height or width requested by a View.
         * WRAP_CONTENT means that the view wants to be just large enough to fit
         * its own internal content, taking its own padding into account.
         */
        public static final int WRAP_CONTENT = -;
           

源码简析

首先对比一下几个重载方法,可以看到除了上面我们用到的两种还有两种。

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
}

public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
}

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
}

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    ...
}
           

不过前三个最终调用的都是:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    ...
}
           

而且我们还可以发现,root != null时,attachToRoot默认为true,布局id会被通过调用getLayout方法生成一个XmlResourceParser对象。我们继续分析inflate方法

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[];
            mConstructorArgs[] = inflaterContext;
            // 首先注意result的初始值为root,也就是我们传进来的
            View result = root;

            try {
                // 尝试找到根节点
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                }

                // 获取当前节点名称
                final String name = parser.getName();

                // 处理merge节点
                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 {
                    // 根据获取到的节点名创建根View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    // 如果我们传递进来一个ViewGroup,那么就会根据我们传递进来的ViewGroup
                    // 生成LayouParams
                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        // 如果attachToRoot为false,那么将LayoutParams添加到根View
                        // 否则会走下面的代码,直接将根View添加到我们传递进来的ViewGroup上
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }

                    // 获取根节点下面所有的子View
                    rInflateChildren(parser, temp, attrs, true);

                    // 如果我们传递进来一个ViewGroup并且attachToRoot为ture
                    // 则将获取到的view添加到我们传递进来的ViewGroup上,同时布局
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // 如果我们没有传递进来ViewGroup或者attachToRoot为false,则将生成的
                    // 根View返回,否则返回root,也就是我们传递进来的ViewGroup
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {

            } catch (Exception e) {

            } finally {

            }
            return result;
        }
    }
           
根据以上分析我们发现这个方法主要有下面几个步骤:
  1. 首先查找根节点,如果整个xml文件解析完毕也没看到根节点,会抛出异常;
  2. 如果查找到的根节点名称是merge标签,会调用rInflate方法继续解析布局,最终返回root;
  3. 如果是其他标签(View、TextView等),会调用createViewFromTag生成布局根View,并调用rInflate递归解析余下的子View,添加至布局根View中,最后视root和attachToRoot参数的情况最终返回view或者root。
从这里我们可以理清root和attachToRoot参数的关系了:
  • root == null, attachToRoot无用:

    当root为空时,attachToRoot是什么都没有意义,此时传进来的布局会被加载成为一个View并直接返回;

    布局根View的android:layout_xxx属性会被忽略。

  • root != null, attachToRoot == true:

    传进来的布局会被加载成为一个View并作为子View添加到root中,最终返回root;

    而且这个布局根节点的android:layout_xxx参数会被解析用来设置View的大小。

  • root != null, attachToRoot == false:

    传进来的布局会被加载成为一个View并直接返回。

    布局根View的android:layout_xxx属性会被解析成LayoutParams并保留。(root只用来参与生成布局根View的LayoutParams)

想必到这不用我说大家也很清楚为什么Demo中通过第一种方式加载布局无法实现我们想要的效果了。

总结

可能以前我们怎么也不明白这些参数的作用,可是今天通过简单的分析源码我们就可以发现其中的端倪,而且要比看别人的介绍印象更加深刻,因此以后遇到不懂不明白的,Read the fucking source code,没有比这更直接有效的了。

其实通过上面简析inflate方法源码的过程,我们对加载xml布局的原理也有了一些简单的了解。其实就是从根节点开始,递归解析xml的每个节点,根据到的节点名通过反射生成一个个View,同时解析该节点的属性作为View的属性,然后根据View的层级关系add到对应的父View(上层节点)中,最终返回一个包含了所有解析好的子View的布局根View。那么具体是不是这样的,且看下回分解。

继续阅读