Android 布局加载之 LayoutInflater

目录

技术答疑,成长进阶,可以加入我的知识星球:音视频领域专业问答的小圈子

Activity 在界面创建时需要将 XML 布局文件中的内容加载进来,正如我们在 ListView 或者 RecyclerView 中需要将 Item 的布局加载进来一样,都是使用 LayoutInflater 来进行操作的。

LayoutInflater 实例的获取有多种方式,但最终是通过(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)来得到的,也就是说加载布局的 LayoutInflater 是来自于系统服务的。

由于 Android 系统源码中关于 Content 部分采用的是装饰模式,Context 的具体功能都是由 ContextImpl 来实现的。通过在 ContextImpl 中找到getSystemService的代码,一路跟进,得知最后返回的实例是PhoneLayoutInflater

1        registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
2                new CachedServiceFetcher<LayoutInflater>() {
3            @Override
4            public LayoutInflater createService(ContextImpl ctx) {
5                return new PhoneLayoutInflater(ctx.getOuterContext());
6            }});
JAVA

LayoutInflater 只是一个抽象类,而 PhoneLayoutInflater 才是具体的实现类。

inflate 方法加载 View

使用 LayoutInflater 时常用方法就是inflate方法了,将一个布局文件 ID 传入并最后解析成一个 View 。

LayoutInflater 加载布局的 inflate 方法也有多种重载形式:

1View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
2View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
JAVA

而这两者的差别就在于是否要将 resource 布局文件加载到 root布局中去。

不过有点需要注意的地方,若 root为 null,则在 xml 布局中为 resource设置的属性会失效,只是单纯的加载布局。

 1				  // temp 是 xml 布局中的顶层 View
 2                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
 3                    ViewGroup.LayoutParams params = null;
 4                    if (root != null) { // root 
 5	                    // root 不为 null 才会生成 layoutParams
 6                        params = root.generateLayoutParams(attrs);
 7                        if (!attachToRoot) {
 8							//  如果不添加到 root 中,则直接把布局参数设置给 temp
 9                            temp.setLayoutParams(params);
10                        }
11                    }
12                    // 加载子 View 
13					rInflateChildren(parser, temp, attrs, true);
14                    if (root != null && attachToRoot) {
15                        root.addView(temp, params);//添加到布局中,则布局参数用到 addView 中去
16                    }
17                    if (root == null || !attachToRoot) {
18                        result = temp;
19                    }
JAVA

跟进createViewFromTag方法查看 View 是如何创建出来的。

 1			View view; // 最后要返回的 View
 2            if (mFactory2 != null) {
 3                view = mFactory2.onCreateView(parent, name, context, attrs); // 是否设置了 Factory2 
 4            } else if (mFactory != null) {
 5                view = mFactory.onCreateView(name, context, attrs); // 是否设置了 Factory
 6            } else {
 7                view = null;
 8            }
 9            if (view == null && mPrivateFactory != null) { // 是否设置了 PrivateFactory
10                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
11            }
12
13            if (view == null) {  // 如果的 Factory 都没有设置过,最后在生成 View
14                final Object lastContext = mConstructorArgs[0];
15                mConstructorArgs[0] = context;
16                try {
17                    if (-1 == name.indexOf('.')) { // 系统控件 
18                        view = onCreateView(parent, name, attrs);
19                    } else { // 非系统控件,自定义的 View 
20                        view = createView(name, null, attrs);
21                    }
22                } finally {
23                    mConstructorArgs[0] = lastContext;
24                }
25            }
JAVA

如果设置过 Factory 接口,那么将由 Factory 中的 onCreateView 方法来生成 View 。

关于 LayoutInflater.Factory 的作用,就是用来在加载布局时可以自行去创建 View,抢在系统创建 View 之前去创建。

关于 LayoutInflater.Factory 的使用场景,现在比较多的就是应用的换肤了。

若没有设置过 Factory 接口,则是判断是否为自定义控件或者系统控件,不管是 onCreateView 方法还是 createView 方法,内部最终都是调用到了 createView 方法,通过它来生成 View 。

 1// 通过反射生成 View 的参数,分别是 Context 和 AttributeSet 类
 2static final Class<?>[] mConstructorSignature = new Class[] {
 3            Context.class, AttributeSet.class};
 4            
 5public final View createView(String name, String prefix, AttributeSet attrs)
 6            throws ClassNotFoundException, InflateException {
 7        Constructor<? extends View> constructor = sConstructorMap.get(name);
 8        Class<? extends View> clazz = null;
 9
10		if (constructor == null) { // 从缓存中得到 View 的构造器,没有则调用 getConstructor
11                clazz = mContext.getClassLoader().loadClass(
12                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
13                if (mFilter != null && clazz != null) {
14                    boolean allowed = mFilter.onLoadClass(clazz);
15                    if (!allowed) {
16                        failNotAllowed(name, prefix, attrs);
17                    }
18                }
19                constructor = clazz.getConstructor(mConstructorSignature);
20                constructor.setAccessible(true);
21                sConstructorMap.put(name, constructor);
22            } else {
23                // If we have a filter, apply it to cached constructor
24                if (mFilter != null) {  // 过滤,是否允许生成该 View
25                    // Have we seen this name before?
26                    Boolean allowedState = mFilterMap.get(name);
27                    if (allowedState == null) {
28                        // New class -- remember whether it is allowed
29                        clazz = mContext.getClassLoader().loadClass(
30                                prefix != null ? (prefix + name) :                  name).asSubclass(View.class);
31                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
32                        mFilterMap.put(name, allowed);
33                        if (!allowed) {
34                            failNotAllowed(name, prefix, attrs);
35                        }
36                    } else if (allowedState.equals(Boolean.FALSE)) {
37                        failNotAllowed(name, prefix, attrs); // 不允许生成该 View
38                    }
39                }
40            }
41        Object[] args = mConstructorArgs;
42        args[1] = attrs;
43        final View view = constructor.newInstance(args); // 通过反射生成 View
44		return view;
JAVA

在 createView 方法内部,首先从 View 的构造器缓存中查找是否有对应的缓存,若没有则生成构造器并且放到缓存中去,若有构造器则看能否通过过滤,是否允许该 View 生成。

最后都满足条件的则是通过 View 的构造器反射生成了 View 。

在生成 View 时采用 Constructor.newInstance调用构造函数,而参数所需要的变量就是mConstructorSignature变量所定义的,分别是 ContextAttributeSet。可以看到,在最后生成 View 时也传入了对应的参数。

采用 Constructor.newInstance的形式反射生成 View ,是为了解耦,只需要有了类名,就可以加载出来。

由此可见,LayoutInflater 加载布局仍然是需要传递 Context的,不光是为了得到 LayoutInflater ,在反射生成 View 时同样会用到。

深度遍历加载布局

如果需要加载的布局只有一个控件,那么 LayoutInflater 返回那个 View 工作也就结束了。

若布局文件中有多个需要加载的 View ,则通过rInflateChildren方法继续加载顶层 View 下的 View ,最后通过rInflate方法来加载。

 1void rInflate(XmlPullParser parser, View parent, Context context,
 2            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
 3        final int depth = parser.getDepth();
 4        int type;
 5		// 若 while 条件不成立,则加载结束了
 6        while (((type = parser.next()) != XmlPullParser.END_TAG ||
 7                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
 8
 9            if (type != XmlPullParser.START_TAG) {
10                continue;
11            }
12            final String name = parser.getName(); // 从 XmlPullParser 中得到 name 出来解析
13            
14            if (TAG_REQUEST_FOCUS.equals(name)) { // name 各种情况下的解析
15                parseRequestFocus(parser, parent);
16            } else if (TAG_TAG.equals(name)) {
17                parseViewTag(parser, parent, attrs);
18            } else if (TAG_INCLUDE.equals(name)) {
19                if (parser.getDepth() == 0) {
20                    throw new InflateException("<include /> cannot be the root element");
21                }
22                parseInclude(parser, context, parent, attrs);
23            } else if (TAG_MERGE.equals(name)) {
24                throw new InflateException("<merge /> must be the root element");
25            } else {
26                final View view = createViewFromTag(parent, name, context, attrs);
27                final ViewGroup viewGroup = (ViewGroup) parent;
28                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
29                rInflateChildren(parser, view, attrs, true); // 继续遍历
30                viewGroup.addView(view, params); // 顶层 View 添加 子 View
31            }
32        }
33
34        if (finishInflate) { // 遍历解析
35            parent.onFinishInflate();
36        }
37    }
JAVA

rInflate方法首先判断是否解析结束了,若没有,则从 XmlPullParser 中加载出下一个 View 进行处理,中间还会对不同的类型进行处理,比如TAG_REQUEST_FOCUSTAG_TAGTAG_INCLUDETAG_MERGE等等。

最后仍然还是通过createViewFromTag来生成 View ,并以这个生成的 View 为父节点,开始深度遍历,继续调用rInflateChildren方法加载布局,并把这个 View 加入到它的父 View 中去。

至于为什么生成 View 的方法名字createViewFromTag从字面上来看是来自于 Tag标签,想必是和 XmlPullParser解析布局生成的内容有关。

参考

  1. http://www.sunnyang.com/661.html?utm_source=tuicool&utm_medium=referral
  2. http://blog.csdn.net/lmj623565791/article/details/51503977
  3. https://segmentfault.com/a/1190000003813755
  4. http://blog.csdn.net/panda1234lee/article/details/9009719

欢迎关注微信公众号:音视频开发进阶

粤ICP备20067247号
使用 Hugo 构建    主题 StackedJimmy 设计,Jacob 修改