源码分析Android LayoutInflater的使用
作者:Yocn
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开头的一段介绍,我们能看到几个重要的信息:
- LayoutInfalter的作用是把XML转化成对应的View对象,需要用
Activity#getLayoutInflater()
或者getSystemService
获取,会绑定当前的Context - 如果需要使用自定义的
Factory
查看替换加载信息,需要用cloneInContext去克隆一个ViewFactory
,然后调用setFactory
设置自定义的Factory - 性能原因,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文件,并根据得到的标签名执行不同的逻辑:
- 首先如果是
merge
标签,会走rInflate方法,方法前面带r
的说明是recurse
递归方法 - 如果不是
merge
标签,执行createViewFromTag
,根据传入的name
和attrs
获取到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
显示隐藏的一个标签,怎么看都像个彩蛋~
然后调用mFactory2
的onCreateView
,如果没有设置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源码分析。
流程图如下:
总结
- LayoutInfalter的作用是把XML转化成对应的View对象,需要用
Activity#getLayoutInflater()
或者getSystemService
获取 - 加载时先判断是否是merge标签,merge标签走递归方法rinflate,否则走createViewFromTag
- createViewFromTag作用是根据xml标签的名字去加载对应的View,使用的是反射的方法
- LayoutInflater.Factory2是设计出来灵活构造View的接口,可以用来实现换肤或者替换View的功能,同时也是AppcompatActivity用来做兼容和版本替换的接口
以上就是源码分析Android LayoutInflater的使用的详细内容,更多关于Android LayoutInflater的资料请关注脚本之家其它相关文章!