LayoutInflater源码分析

LayoutInflater

开头先附一段LayoutInflater类的注释简介

/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 * objects. It is never used directly. Instead, use
 * {@link android.app.Activity#getLayoutInflater()} or
 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
 * that is already hooked up to the current context and correctly configured
 * for the device you are running on.
 *
 * To create a new LayoutInflater with an additional {@link Factory} for your
 * own views, you can use {@link #cloneInContext} to clone an existing
 * ViewFactory, and then call {@link #setFactory} on it to include your
 * Factory.
 *
 * 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;
 * it only works with an XmlPullParser returned from a compiled resource
 * (R.<em>something</em> file.)
 */

这是LayoutInflater开头的一段介绍,我们能看到几个重要的信息:

  1. LayoutInfalter的作用是把XML转化成对应的View对象,需要用Activity#getLayoutInflater()或者getSystemService获取,会绑定当前的Context
  2. 如果需要使用自定义的Factory查看替换加载信息,需要用cloneInContext去克隆一个ViewFactory,然后调用setFactory设置自定义的Factory
  3. 性能原因,inflate会在build阶段进行,无法用来加载一个外部文本XML文件,只能加载R.xxx.xxx这种处理好的资源文件。
//LayoutInflater.java
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    //root是否为null来决定attachToRoot是否为true。
        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();
        }
    }
//三个inflate方法最终都会调用到下面这个三个参数的inflate方法。
    /**
     * parser XML节点包含了View的层级描述
     * root 需要attached到的根目录,如果attachToRoot为true则root必须不为null。
     * attachToRoot 加载的层级是否需要attach到rootView,
     * return attachToRoot为true,就返回root,反之false就返回加载的XML文件的根节点View。
     */
    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 {
                // 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 (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) {
                        // 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) {
...
            }
            return result;
        }
    }

inflate方法使用XmlPullParser解析XML文件,并根据得到的标签名执行不同的逻辑:
1、首先如果是merge标签,会走rInflate方法,方法前面带r的说明是recurse递归方法
2、如果不是merge标签,执行createViewFromTag,根据传入的nameattrs获取到name对应的rootView并且添加到root里面。

针对merge标签,如果是merge标签必须有root并且必须attachToRoot==true,否则直接抛异常,所以我们得知merge必须作为root标签使用,并且不能用在子标签中①,rInflate方法中也会针对merge标签进行检查,保证merge标签不会出现在子标签中,后面会有介绍。
检查通过则调用rInflate(parser, root, inflaterContext, attrs, false)方法,递归遍历root的层级,解析加载childrenView挂载到parentView下面,rinflate详细解析可以看rinflate

如果不是merge标签则调用createViewFromTag(root, name, inflaterContext, attrs),这个方法的作用是加载名字为name的view,根据name反射方式创建对应的View,根据传入的attrs构造Params设置给View,返回创建好的View。
当然这只是创建了一个View,需要再调用rInflateChildren(parser, temp, attrs, true),这个方法也是一个递归方法,它的作用是根据传入的parser包含的层级,加载此层级的子View并挂载到temp下面。

createViewFromTag
    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        // 如果传入的attr中包含theme属性,则使用此attr中的theme。
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }

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

            return view;
        } catch (Exception e) {
            ...
        }
    }

先看当前标签的attr属性里面是否设置了theme,如果设置了就用当前标签的theme属性,绑定到context上面。
这里很有意思的是特殊判断了一个TAG_1995,也就是blink,一个将包裹的内容每隔500ms显示隐藏的一个标签,怎么看都像个彩蛋~
然后调用mFactory2onCreateView,如果没有设置mFactory2就尝试mFactory,否则调用mPrivateFactory,mFactory2和mFactory后面再说,这里先往后走。
如果还是没有加载到view,先判断name,看名字里是不是有.,如果没有就表明是Android原生的View,最终都会调用到createView方法,onCreateView最终会调用到createView(name, "android.view.", attrs);,会在View名字天面添加"android.view."前缀。

下面是默认的createView的实现:

    @Nullable
    public final View createView(@NonNull Context viewContext, @NonNull String name,
            @Nullable String prefix, @Nullable AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Objects.requireNonNull(viewContext);
        Objects.requireNonNull(name);
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
                        mContext.getClassLoader()).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, viewContext, 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 = Class.forName(prefix != null ? (prefix + name) : name, false,
                                mContext.getClassLoader()).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, viewContext, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, viewContext, attrs);
                    }
                }
            }

            Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = viewContext;
            Object[] args = mConstructorArgs;
            args[1] = attrs;

            try {
                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]));
                }
                return view;
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        } catch (Exception e) {
            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

这个方法可以看到View是怎么创建出来的,用类的全限定名拿到class信息,有一个sConstructorMap缓存类的constructor,如果能拿到有效的构造器就不再重复创建来提升效率,如果没有缓存的构造器,就反射得到构造器并添加到sConstructorMap中以便后面使用。这里有个mFilter来提供自定义选项,用户可以自定义哪些类不允许构造。
拿到构造器之后,实际上newInstance是调用了两View个参数的构造方法。第一个参数是Context,第二个参数是attrs,这样我们就得到了需要加载的View。

这里可以结合LayoutInflater.Factory2一起来看,Activity实际上是实现了LayoutInflater.Factory2接口的:

//Activity.java
    public View onCreateView(@NonNull String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
        return null;
    }

所以我们可以直接在Activity里面重写onCreateView方法,这样就可以根据View的名字来实现我们的一些操作,比如换肤的操作,比如定义一个名字来表示某种自定义View。可以看这样一个用法:

    <PlaceHolder
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="include LinearLayout"
        android:textColor="#fff"
        android:textSize="15sp" />

然后我们在重写的onCreateView里面判断name:

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if ("PlaceHolder".equals(name)) {
            return new TextView(this, attrs);
        }
        return super.onCreateView(name, context, attrs);
    }

这样其实就不拘泥于名字可以自己创建对应的View,这样其实可以用在多个module依赖的时候,如果在moduleA中得不到moduleB的某个自定义View,可以使用一个这样的方式来在moudleA中暂时的用来做一个占位标记,在moduleB中做一个判断。
同样的,通过上面的代码我们知道LayoutInflater是通过反射拿到构造方法来创建View的,那众所周知反射是有性能损耗的,那么我们可以在onCreateView方法中判断名字直接new出来,当然也可以跟AppcompatActivity里面做的一样,做一些兼容的操作来替换成不同版本的View:

public final View createView(View parent, final String name, @NonNull Context context,
        View view = null;
        switch (name) {
            case "TextView":
                view = new AppCompatTextView(context, attrs);
                break;
            case "ImageView":
                view = new AppCompatImageView(context, attrs);
                break;
            case "Button":
                view = new AppCompatButton(context, attrs);
                break;
            case "EditText":
                view = new AppCompatEditText(context, attrs);
                break;
            case "Spinner":
                view = new AppCompatSpinner(context, attrs);
                break;
            case "ImageButton":
                view = new AppCompatImageButton(context, attrs);
                break;
            ...
        }
...
        return view;
    }

还没有展开说rinflate,篇幅限制,放到另外一篇文章中去分析,rinflate源码分析
流程图如下:

流程图

总结:
  1. LayoutInfalter的作用是把XML转化成对应的View对象,需要用Activity#getLayoutInflater()或者getSystemService获取
  2. 加载时先判断是否是merge标签,merge标签走递归方法rinflate,否则走createViewFromTag
  3. createViewFromTag作用是根据xml标签的名字去加载对应的View,使用的是反射的方法
  4. LayoutInflater.Factory2是设计出来灵活构造View的接口,可以用来实现换肤或者替换View的功能,同时也是AppcompatActivity用来做兼容和版本替换的接口
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269