
Android LayoutInflater 源码解析
备注:本文基于 Android 8.1.0。
1、LayoutInflater 简介
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.getLayoutInflater() or Context.getSystemService(Class) 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.
翻译过来就是:LayoutInflater 的作用就是将XML布局文件实例化为相应的 View 对象,需要通过Activity.getLayoutInflater() 或 Context.getSystemService(Class) 来获取与当前Context已经关联且正确配置的标准LayoutInflater。
总共有三种方法来获取 LayoutInflater:
Activity.getLayoutInflater();
Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
LayoutInflater.from(context);
事实上,这三种方法之间是有关联的:
Activity.getLayoutInflater() 最终会调用到 PhoneWindow 的构造方法,实际上最终调用的就是方法三;
而方法三最终会调用到方法二 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
2、inflate 方法解析
image
LayoutInflater 的 inflate 方法总共有四个,属于重载的关系,最终都会调用到 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法。
备注:以下源码中有七条备注。
备注:根据以上源码,我们也可以分析出来 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 不同参数值带来的影响:
如果root为null,attachToRoot将失去作用,设置任何值都没有意义;
如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root;
如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效;
在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true;
3、rInflate 方法解析
以上代码中我们还有两个方法没有分析:rInflate 和 rInflateChildren ;而 rInflateChildren 实际上是调用了rInflate;
备注:以下源码中有六条备注。
总结:
首先进行View的合理性校验,include、merge等标签;
通过 createViewFromTag 创建出 View 对象;
如果是 ViewGroup,则重复以上步骤;
add View 到相应的 parent 中;
4、createViewFromTag 方法解析
备注:以下源码中有六条备注。
总结:
createViewFromTag 方法比较简单,首先尝试通过 Factory 来创建View;
如果没有 Factory 的话则通过 createView 来创建View;
5、createView 方法解析
备注:以下源码中有三条备注。
总结:
createView 方法也比较简单,通过反射来创建的 View 对象;
6、总结
通过本文我们学习到 LayoutInflater 创建 View的过程,也知道了 inflate 方法不同参数的意义,以及开发中遇到的一些异常在源码中的根源。可以看到从布局中 inflate 一个个具体的 View 的过程其实也很简单:
通过 XML 的 Pull 解析方式获取 View 的标签;
通过标签以反射的方式来创建 View 对象;
如果是 ViewGroup 的话则会对子 View 遍历并重复以上步骤,然后 add 到父 View 中;
与之相关的几个方法:inflate ——》 rInflate ——》 createViewFromTag ——》 createView ;
参考
《Android LayoutInflater原理分析,带你一步步深入了解View(一)》
LayoutInflater
