LayoutInflater源码分析

2024-02-03 05:48

本文主要是介绍LayoutInflater源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

最近又遇到RecyclerView的item最外层布局参数失效的问题,之前都没有去了解真正的原因,现在正好有空探寻一下这个问题,就从了解源码开始吧。

View的inflate()

平时我经常使用View.inflate(),它是View的一个静态方法,看到源码:

   public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {LayoutInflater factory = LayoutInflater.from(context);return factory.inflate(resource, root);}

其中调用了LayoutInflater的静态方法from()

    /*** Obtains the LayoutInflater from the given context.*/public static LayoutInflater from(Context context) {LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);if (LayoutInflater == null) {throw new AssertionError("LayoutInflater not found.");}return LayoutInflater;}

这里根据上下文,从系统获取了一个LayoutInfalter的实例对象。

LayoutInflater的infalte()

然后接着上面,用这个获取的对象去调用LayoutInfalter的inflate():

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {return inflate(resource, root, root != null);}public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {final Resources res = getContext().getResources();if (DEBUG) {Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("+ Integer.toHexString(resource) + ")");}final XmlResourceParser parser = res.getLayout(resource);try {return inflate(parser, root, attachToRoot);} finally {parser.close();}}

其中可以看到获取了一个xml解析器,获取解析器的时候把要填充的xml的ID作为了参数,然后又去调用了一个inflate()的重载:

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {synchronized (mConstructorArgs) {Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");final Context inflaterContext = mContext;final AttributeSet attrs = Xml.asAttributeSet(parser);Context lastContext = (Context) mConstructorArgs[0];mConstructorArgs[0] = inflaterContext;// 假设该方法返回的结果为根View, 即方法参数rootView 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 (DEBUG) {System.out.println("**************************");System.out.println("Creating root view: "+ name);System.out.println("**************************");}if (TAG_MERGE.equals(name)) {// 如果要填充的xml根布局为merge标签if (root == null || !attachToRoot) {// 如果root为空或者不需要将创建出来的View添加到root中直接会抛异常throw new InflateException("<merge /> can be used only with a valid "+ "ViewGroup root and attachToRoot=true");}// 创建并填充子ViewrInflate(parser, root, inflaterContext, attrs, false);} else {// Temp is the root view that was found in the xml// 根据xml,创建对应的View,叫tempfinal View temp = createViewFromTag(root, name, inflaterContext, attrs);ViewGroup.LayoutParams params = null;if (root != null) {// 如果传进来的root不为空if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if supplied// 那么根据xml中配置的属性,去获取布局参数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不需要被添加到root中,就给他设置布局参数temp.setLayoutParams(params);}}if (DEBUG) {System.out.println("-----> start inflating children");}// Inflate all children under temp against its context.// 创建并填充子ViewrInflateChildren(parser, temp, attrs, true);if (DEBUG) {System.out.println("-----> done inflating children");}// We are supposed to attach all the views we found (int temp)// to root. Do that now.if (root != null && attachToRoot) {// 如果root不为空,并且temp需要被添加到root中// 那就把temp添加到root中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为空或者temp不需要被添加到root中// 那么该方法返回的View就是temp// 否则返回rootresult = temp;}}} catch (XmlPullParserException e) {final InflateException ie = new InflateException(e.getMessage(), e);ie.setStackTrace(EMPTY_STACK_TRACE);throw ie;} catch (Exception e) {final InflateException ie = new InflateException(parser.getPositionDescription()+ ": " + e.getMessage(), e);ie.setStackTrace(EMPTY_STACK_TRACE);throw ie;} finally {// Don't retain static reference on context.mConstructorArgs[0] = lastContext;mConstructorArgs[1] = null;Trace.traceEnd(Trace.TRACE_TAG_VIEW);}return result;}}

以上的这个方法信息量很大,我写了很多中文注释在代码中。

关于方法返回值

我们可以知道,如果root为空或者我当前要创建的View不需要添加到root中,那么返回的就是我要创建的View,反之返回的是root。

外层布局失效的问题

我写的代码是这样的View view = View.inflate(context, R.layout.item_pic, null);,然后根据函数调用链:

// 第一步:
View view = View.inflate(context, R.layout.item_pic, null);
// 第二步
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {// 就变成了infalte(R.layout.item_pic, null, false);return inflate(resource, root, root != null);
}
……
// 最后就进入了上面的方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot){……
}

因为我最初传入的root就是空啊,所以我最后只是创建了View,返回了View 但是没有给他设置布局参数,所以出现外层布局失效的问题。

那我创建RecyclerView的item时,直接把RecyclerView作为参数root传进去可以吗?答案是不行的,因为这样的话调用inflate()的时候是这样的:inflate(resource, recyclerView, true)。然后你创建了View,并且把它添加到了RecyclerView。然而RecyclerView接收到你返回的View之后,还会自动把它添加到本身,这样又会出现重复添加的问题

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first

最佳解决方案就是直接使用LayoutInflater:View view = LayoutInflater.from(context).inflate(R.layout.item_pic, recyclerView, false);
这样的话,回去看下inflate()中的逻辑,发现view会被设置布局参数,并且不会直接被添加到recyclerView中。

LayoutInflater的createViewFromTag()

在inflate()中使用createViewFromTag()去创建xml对应的View,以下是主要代码:

    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,boolean ignoreThemeAttr) {……try {View view;// 可以设置LayoutInflater的Factory来自行解析View,默认这些Factory都为空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) {// 没有Factory的情况下,通过LayoutInflater的onCreateView()或者createView()去创建Viewfinal Object lastContext = mConstructorArgs[0];mConstructorArgs[0] = context;try {if (-1 == name.indexOf('.')) {// 创建原生的View// 会在onCreateView()的函数调用链中补充前缀"android.view."// 最终也会调用createView()view = onCreateView(parent, name, attrs);} else {// 创建自定义View// 我们在xml里写的都是全类名,标签中包含"."view = createView(name, null, attrs);}} finally {mConstructorArgs[0] = lastContext;}}return view;} ……}

以上说到的Factory,我之前在TintContextWrapper强转Activity失败原因深度探索分析到过,当我们使用AppCompatActivity时,会设置Factory2为AppCompatViewInflater,然后View都会走AppCompatViewInflatercreateView()

LayoutInflater的createView():

     /*** Low-level function for instantiating a view by name. This attempts to* instantiate a view class of the given <var>name</var> found in this* LayoutInflater's ClassLoader.* * <p>* There are two things that can happen in an error case: either the* exception describing the error will be thrown, or a null will be* returned. You must deal with both possibilities -- the former will happen* the first time createView() is called for a class of a particular name,* the latter every time there-after for that class name.* * @param name The full name of the class to be instantiated.* @param attrs The XML attributes supplied for this instance.* * @return View The newly instantiated view, or null.*/public final View createView(String name, String prefix, AttributeSet attrs)throws ClassNotFoundException, InflateException {// 从缓存中获取View的构造函数Constructor<? extends View> constructor = sConstructorMap.get(name);if (constructor != null && !verifyClassLoader(constructor)) {constructor = null;sConstructorMap.remove(name);}Class<? extends View> clazz = null;try {Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);if (constructor == null) {// 如果缓存中没有需要的构造函数// Class not found in the cache, see if it's real, and try to add it// 如果prefix不为空,那么构造完整View路径,并且加载该类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);}}// 从Class对象中获取构造函数constructor = clazz.getConstructor(mConstructorSignature);constructor.setAccessible(true);// 将构造函数存入缓存中sConstructorMap.put(name, constructor);} else {// If we have a filter, apply it to cached constructorif (mFilter != null) {// Have we seen this name before?Boolean allowedState = mFilterMap.get(name);if (allowedState == null) {// New class -- remember whether it is allowedclazz = 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[] args = mConstructorArgs;args[1] = attrs;// 通过反射构造Viewfinal View view = constructor.newInstance(args);if (view instanceof ViewStub) {// Use the same context when inflating ViewStub later.// 如果是ViewStub,延迟加载final ViewStub viewStub = (ViewStub) view;viewStub.setLayoutInflater(cloneInContext((Context) args[0]));}return view;}……}

对于创建View使用反射其实我比较疑惑,方法注释说的是这个createView()是低版本上使用的方法,用来从类加载器中加载给定的View。后来我百度了下,可能是为了实现全局换肤这种类似的操作。

LayoutInflater的rInflate()

通过createViewFromTag()创建了View之后,只是创建了根布局的View,那其中的子View呢,回顾inflate()中的代码,我们会发现rInflate()rInflateChildren()这两个方法,rInflateChildren()调用的还是rInflate()

    void rInflate(XmlPullParser parser, View parent, Context context,AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {// 获取树的深度final int depth = parser.getDepth();int type;// 深度优先遍历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)) {parseRequestFocus(parser, parent);} else if (TAG_TAG.equals(name)) {parseViewTag(parser, parent, attrs);} else if (TAG_INCLUDE.equals(name)) {if (parser.getDepth() == 0) {throw new InflateException("<include /> cannot be the root element");}// 解析inclued标签parseInclude(parser, context, parent, attrs);} else if (TAG_MERGE.equals(name)) {// merge标签只能是根布局// 到了这里说明不是根布局,抛出异常throw new InflateException("<merge /> must be the root element");} else {// 创建Viewfinal View view = createViewFromTag(parent, name, context, attrs);final ViewGroup viewGroup = (ViewGroup) parent;// 创建布局参数final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);// 递归地去遍历子树rInflateChildren(parser, view, attrs, true);// 将创建的View加入父布局viewGroup.addView(view, params);}}if (finishInflate) {parent.onFinishInflate();}}

布局优化总结

从以上的源码分析,我们其实可以得出如下结论:

  1. merge标签作为填充的xml的根布局时,必须指定一个父元素并且设置attachToRoot属性为true。

  2. 我们通常使用ViewStub来做预加载处理,来改善页面加载速度和提高流畅性。

  3. include标签用来复用布局。

在分析源码到用反射创建View的时候,我发现了一篇比较不错的文章Android 中LayoutInflater(布局加载器)系列博文说明。

这篇关于LayoutInflater源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/673141

相关文章

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步

Redis主从复制实现原理分析

《Redis主从复制实现原理分析》Redis主从复制通过Sync和CommandPropagate阶段实现数据同步,2.8版本后引入Psync指令,根据复制偏移量进行全量或部分同步,优化了数据传输效率... 目录Redis主DodMIK从复制实现原理实现原理Psync: 2.8版本后总结Redis主从复制实

锐捷和腾达哪个好? 两个品牌路由器对比分析

《锐捷和腾达哪个好?两个品牌路由器对比分析》在选择路由器时,Tenda和锐捷都是备受关注的品牌,各自有独特的产品特点和市场定位,选择哪个品牌的路由器更合适,实际上取决于你的具体需求和使用场景,我们从... 在选购路由器时,锐捷和腾达都是市场上备受关注的品牌,但它们的定位和特点却有所不同。锐捷更偏向企业级和专