Android LayoutInflater分析

今天分析下经常使用加载布局的layoutInflater
我们在加载布局的时候都会主动或者被动的用到 LayoutInflater ,比如 Activity 的setContentView方法和Fragment的onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)回调等。LayoutInflater 的作用就是把布局文件xml实例化为相应的View组件。我们可以通过三种方法获取 LayoutInflater:

1.Activity.getLayoutInflater();
2.LayoutInflater.from(context);
3.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

每个方法都和 Context 相关联,其中方法1和方法2最终都会通过方法3来实现。
获取到 LayoutInflater 后,通过调用inflate方法来实例化布局。而inflate方法由很多重载,我们常用的是inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot),所有 inflate 方法最终会调用到 inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)。下面就从这个方法入手,开始分析 LayoutInflater 的源码。

inflate方法
先看一下inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)的三个参数:

  1. XmlPullParser parser:很显然是一个 XML 解析器,这个解析器就是 LayoutInflater 所要加载的 XML 布局转化来的,通过 PULL 方式解析。
  2. ViewGroup root:装载要加载的 XML 布局的根容器,比如,在 Activity 的setContentView方法中就是 id 为android.R.id.content的 FrameLayout 根布局了。
  3. boolean attachToRoot:是否将所解析的布局添加到根容器中,同时也影响了所解析布局的宽高。

被广泛讨论的是root和attachToRoot的不同传参对被加载的布局文件的影响,下面看代码。

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final Context inflaterContext = mContext;
            // 将parser转成AttributeSet接口,用来读取xml中设置的View属性
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root; // 此方法返回的View,默认是root
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                ...
                final String name = parser.getName(); // 获取当前的标签名
                ...
                if (TAG_MERGE.equals(name)) { // 处理<merge>标签
                    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
                    // 创建View对象
                    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); // 获取根View的宽高
                        if (!attachToRoot) { // 如果attachToRoot为false,则给根View设置宽高
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }
                    ...
                    // Inflate all children under temp against its context.
                    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不空,且attachToRoot为true,则将根View添加到容器中
                        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) {
                        // 如果root空或者attachToRoot为false,则将返回结果设置为根View
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {
                ...
            } catch (Exception e) {
                ...
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
            // 要么是root,要么是创建的根View
            return result;
        }
    }

从代码中可以看出root和attachToRoot不同传参的影响:

  1. 如果root不为null,attachToRoot设为true,则会将加载的布局添加到一个父布局中,即root,并且返回root;
  2. 如果root不为null,attachToRoot设为false,则会对布局文件最外层的所有layout属性进行设置,并且返回该布局的根View,当该view被添加到父view当中时,这些layout属性会自动生效;
  3. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义,返回的也是要加载的布局的根View;

rInflate方法

从上面的方法中可以看到处理<merge>标签时会调用rInflate,处理子View时会调用rInflateChildren方法。其实rInflateChildren中调用的是rInflate,而rInflate也调用了rInflateChildren,从而形成了递归调用,也就是递归处理子View。

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            final String name = parser.getName();
            if (TAG_REQUEST_FOCUS.equals(name)) {
                // 处理<requestFocus>标签
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                // 处理<tag>标签
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                // 处理<include>标签
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) { // <merge>标签异常
                throw new InflateException("<merge /> must be the root element");
            } else { // 创建View对象
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true); // 递归处理孩子节点
                viewGroup.addView(view, params); // 将View添加到父布局中
            }
        }
        if (pendingRequestFocus) { // 父布局处理焦点
            parent.restoreDefaultFocus();
        }
        if (finishInflate) { // 结束加载
            parent.onFinishInflate();
        }
    }

该方法中会处理<requestFocus>、<tag>、<include>、<merge>和普通View标签。其中:

  1. <requestFocus>是重新定位焦点的,调用的consumeChildElements方法其实没干什么事,只是简单的把该标签消费结束掉。
  2. <tag>标签一般很少用,它主要用来标记View,给View设置一个标签值,例如:
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" >

        <tag android:id="@+id/tag"
            android:value="hello" />

    </TextView>
    
    findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 试一下tag标签
                Toast.makeText(MainActivity.this, (String) v.getTag(R.id.tag), Toast.LENGTH_SHORT).show();
            }
        });

在ListView的自定义Adapter中,应该都有用到过View的setTag方法,即:使用ViewHolder来重复利用View。
parseViewTag方法:

private void parseViewTag(XmlPullParser parser, View view, AttributeSet attrs)
            throws XmlPullParserException, IOException {
        final Context context = view.getContext();
        final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ViewTag);
        // 读取tag的id
        final int key = ta.getResourceId(R.styleable.ViewTag_id, 0);
        // 读取tag的值
        final CharSequence value = ta.getText(R.styleable.ViewTag_value);
        // 给View设置该tag
        view.setTag(key, value);
        ta.recycle();
        // 结束该标签(子View无效)
        consumeChildElements(parser);
    }
  1. <include>标签不能是根标签,parseInclude方法单独分析。
  2. <merge>标签只能是根标签,这里会抛异常。

parseInclude方法

private void parseInclude(XmlPullParser parser, Context context, View parent,
            AttributeSet attrs) throws XmlPullParserException, IOException {
        int type;
        if (parent instanceof ViewGroup) { // 必须在ViewGroup里才有效
            // 处理theme属性
            ...
            // If the layout is pointing to a theme attribute, we have to
            // massage the value to get a resource identifier out of it.
            // 拿到layout指定的布局
            int layout = attrs.getAttributeResourceValue(null, ATTR_LAYOUT, 0);
            ...
            if (layout == 0) { // 必须是合法的id
                final String value = attrs.getAttributeValue(null, ATTR_LAYOUT);
                throw new InflateException("You must specify a valid layout "
                        + "reference. The layout ID " + value + " is not valid.");
            } else { // 类似于inflate的处理
                // 拿到layout的解析器
                final XmlResourceParser childParser = context.getResources().getLayout(layout);
                try {
                    final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
                    while ((type = childParser.next()) != XmlPullParser.START_TAG &&
                            type != XmlPullParser.END_DOCUMENT) {
                        // Empty.
                    }
                    if (type != XmlPullParser.START_TAG) {
                        throw new InflateException(childParser.getPositionDescription() +
                                ": No start tag found!");
                    }
                    // layout的根标签
                    final String childName = childParser.getName();
                    if (TAG_MERGE.equals(childName)) { // 处理<merge>
                        // The <merge> tag doesn't support android:theme, so
                        // nothing special to do here.
                        rInflate(childParser, parent, context, childAttrs, false);
                    } else { // 处理View
                        final View view = createViewFromTag(parent, childName,
                                context, childAttrs, hasThemeOverride);
                        final ViewGroup group = (ViewGroup) parent;
                        final TypedArray a = context.obtainStyledAttributes(
                                attrs, R.styleable.Include);
                        // 获取<include>里设置的id
                        final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
                        // 获取<include>里设置的visibility
                        final int visibility = a.getInt(R.styleable.Include_visibility, -1);
                        a.recycle();
                        ViewGroup.LayoutParams params = null;
                        try { // 获取<include>里设置的宽高
                            params = group.generateLayoutParams(attrs);
                        } catch (RuntimeException e) {
                            // Ignore, just fail over to child attrs.
                        }
                        if (params == null) {
                            // 获取layout里设置的宽高
                            params = group.generateLayoutParams(childAttrs);
                        }
                        // <include>里设置的宽高优先于layout里设置的
                        view.setLayoutParams(params);
                        // Inflate all children.
                        rInflateChildren(childParser, view, childAttrs, true);
                        if (id != View.NO_ID) {
                            // include里设置的id优先级高
                            view.setId(id);
                        }
                        // include里设置的visibility优先级高
                        switch (visibility) {
                            case 0:
                                view.setVisibility(View.VISIBLE);
                                break;
                            case 1:
                                view.setVisibility(View.INVISIBLE);
                                break;
                            case 2:
                                view.setVisibility(View.GONE);
                                break;
                        }
                        group.addView(view);
                    }
                } finally {
                    childParser.close();
                }
            }
        } else {
            throw new InflateException("<include /> can only be used inside of a ViewGroup");
        }
        LayoutInflater.consumeChildElements(parser);
    }
  1. include里必须设置layout属性,且layout的id必须合法;
  2. include里设置的id优先级高于layout里设置的id,即:两者同时设置时,后者会失效;
  3. include里设置的width和height属性优先级高于layout里设置的宽高;
  4. include里设置的visibility属性优先级高于layout设置的visibility。

createViewFromTag方法

正常View标签都是通过createViewFromTag来创建对应的View对象的。

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) { 
            // 真正的View标签名存在class属性中
            name = attrs.getAttributeValue(null, "class");
        }
        ...
        try {
            View view;
            if (mFactory2 != null) { // 先使用Factory2
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) { // 再使用Factory
                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 {
                    // 通过标签名中是否包含'.'来区分是否为自定义View
                    if (-1 == name.indexOf('.')) {
                        // 处理系统View
                        view = onCreateView(parent, name, attrs);
                    } else { // 自定义View用的是全限定类名
                        // 处理自定义View
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            return view;
        } catch (InflateException e) {
            ...
        } catch (ClassNotFoundException e) {
            ...
        } catch (Exception e) {
            ...
        }
    }
  1. 优先通过Factory2和Factory来创建View,这两个Factory等会再说;
  2. 通过标签名中是否包含'.'来区分待创建的View是自定义View还是系统View;
  3. 系统View会在onCreateView方法中添加android.view.前缀,然后交由createView处理。

createView方法

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        // 有缓存
        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) { // 第一次则通过反射创建constructor
                // Class not found in the cache, see if it's real, and try to add it
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                // 使用的是包含Context, AttributeSet这两个参数的构造函数
                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 = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);
                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }
            Object lastContext = mConstructorArgs[0];
            if (mConstructorArgs[0] == null) {
                // Fill in the context if not already within inflation.
                mConstructorArgs[0] = mContext;
            }
            Object[] args = mConstructorArgs;
            args[1] = attrs;
            // 反射创建View实例对象
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // 如果是ViewStub则懒加载
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            mConstructorArgs[0] = lastContext;
            return view;
        } 
        ...
    }

通过反射待创建View的构造函数(两个参数:Context和AttributeSet的构造函数)来实例化View对象,如果是ViewStub对象还会进行懒加载。

LayoutInflater.Factory/Factory2

通过以上流程,使用LayoutInflater的infalte方法加载布局文件的整体流程就分析完了。但出现了Factory2和Factory类,它们会优先创建View,我们来看看着两个类到底是什么!
它们都是LayoutInflater的内部类——两个接口:

    public interface Factory {
        public View onCreateView(String name, Context context, AttributeSet attrs);
    }

    public interface Factory2 extends Factory {
        public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
    }

Factory2继承了Factory,增加了一个带View parent参数的onCreateView重载方法。它们是在createViewFromTag中被调用的,默认为null,说明开发人员可以自定义这两个Factory,则通过它们可以改造待加载XML布局中的View标签,来使用自定义规则创建View。
来看一下它们的设置方法:

    public void setFactory(Factory factory) {
        if (mFactorySet) {
            throw new IllegalStateException("A factory has already been set on this LayoutInflater");
        }
        // 和setFactory2类似
        ...
        }
    }

    public void setFactory2(Factory2 factory) {
        if (mFactorySet) { // 只能设置一次
            throw new IllegalStateException("A factory has already been set on this LayoutInflater");
        }
        if (factory == null) {
            throw new NullPointerException("Given factory can not be null");
        }
        mFactorySet = true;
        if (mFactory == null) {
            mFactory = mFactory2 = factory;
        } else { // 合并原有的Factory
            mFactory = mFactory2 = new FactoryMerger(factory, factory, mFactory, mFactory2);
        }
    }

可以看到Factory和Factory2只能设置一次,否则会抛异常。
这两个Factory的区别是什么?

Factory2 是API 11 被加进来的;
Factory2 继承自 Factory,也就说现在直接使用Factory2即可;
Factory2 可以对创建 View 的 Parent 进行操作;

总结

LayoutInflater的相关分析就这么多,文章有点长,慢慢看吧!

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

推荐阅读更多精彩内容