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

相关文章

[职场] 公务员的利弊分析 #知识分享#经验分享#其他

公务员的利弊分析     公务员作为一种稳定的职业选择,一直备受人们的关注。然而,就像任何其他职业一样,公务员职位也有其利与弊。本文将对公务员的利弊进行分析,帮助读者更好地了解这一职业的特点。 利: 1. 稳定的职业:公务员职位通常具有较高的稳定性,一旦进入公务员队伍,往往可以享受到稳定的工作环境和薪资待遇。这对于那些追求稳定的人来说,是一个很大的优势。 2. 薪资福利优厚:公务员的薪资和

springboot家政服务管理平台 LW +PPT+源码+讲解

3系统的可行性研究及需求分析 3.1可行性研究 3.1.1技术可行性分析 经过大学四年的学习,已经掌握了JAVA、Mysql数据库等方面的编程技巧和方法,对于这些技术该有的软硬件配置也是齐全的,能够满足开发的需要。 本家政服务管理平台采用的是Mysql作为数据库,可以绝对地保证用户数据的安全;可以与Mysql数据库进行无缝连接。 所以,家政服务管理平台在技术上是可以实施的。 3.1

高仿精仿愤怒的小鸟android版游戏源码

这是一款很完美的高仿精仿愤怒的小鸟android版游戏源码,大家可以研究一下吧、 为了报复偷走鸟蛋的肥猪们,鸟儿以自己的身体为武器,仿佛炮弹一样去攻击肥猪们的堡垒。游戏是十分卡通的2D画面,看着愤怒的红色小鸟,奋不顾身的往绿色的肥猪的堡垒砸去,那种奇妙的感觉还真是令人感到很欢乐。而游戏的配乐同样充满了欢乐的感觉,轻松的节奏,欢快的风格。 源码下载

高度内卷下,企业如何通过VOC(客户之声)做好竞争分析?

VOC,即客户之声,是一种通过收集和分析客户反馈、需求和期望,来洞察市场趋势和竞争对手动态的方法。在高度内卷的市场环境下,VOC不仅能够帮助企业了解客户的真实需求,还能为企业提供宝贵的竞争情报,助力企业在竞争中占据有利地位。 那么,企业该如何通过VOC(客户之声)做好竞争分析呢?深圳天行健企业管理咨询公司解析如下: 首先,要建立完善的VOC收集机制。这包括通过线上渠道(如社交媒体、官网留言

基于Java医院药品交易系统详细设计和实现(源码+LW+调试文档+讲解等)

💗博主介绍:✌全网粉丝10W+,CSDN作者、博客专家、全栈领域优质创作者,博客之星、平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌💗 🌟文末获取源码+数据库🌟 感兴趣的可以先收藏起来,还有大家在毕设选题,项目以及论文编写等相关问题都可以给我留言咨询,希望帮助更多的人  Java精品实战案例《600套》 2023-2025年最值得选择的Java毕业设计选题大全:1000个热

美容美发店营销版微信小程序源码

打造线上生意新篇章 一、引言:微信小程序,开启美容美发行业新纪元 在数字化时代,微信小程序以其便捷、高效的特点,成为了美容美发行业营销的新宠。本文将带您深入了解美容美发营销微信小程序,探讨其独特优势及如何助力商家实现业务增长。 二、微信小程序:美容美发行业的得力助手 拓宽客源渠道:微信小程序基于微信社交平台,轻松实现线上线下融合,帮助商家快速吸引潜在客户,拓宽客源渠道。 提升用户体验:

风水研究会官网源码系统-可展示自己的领域内容-商品售卖等

一款用于展示风水行业,周易测算行业,玄学行业的系统,并支持售卖自己的商品。 整洁大气,非常漂亮,前端内容均可通过后台修改。 大致功能: 支持前端内容通过后端自定义支持开启关闭会员功能,会员等级设置支持对接官方支付支持添加商品类支持添加虚拟下载类支持自定义其他类型字段支持生成虚拟激活卡支持采集其他站点文章支持对接收益广告支持文章评论支持积分功能支持推广功能更多功能,搭建完成自行体验吧! 原文

HTML5文旅文化旅游网站模板源码

文章目录 1.设计来源文旅宣传1.1 登录界面演示1.2 注册界面演示1.3 首页界面演示1.4 文旅之行界面演示1.5 文旅之行文章内容界面演示1.6 关于我们界面演示1.7 文旅博客界面演示1.8 文旅博客文章内容界面演示1.9 联系我们界面演示 2.效果和源码2.1 动态效果2.2 源代码2.3 源码目录 源码下载万套模板,程序开发,在线开发,在线沟通 作者:xcLeigh

打包体积分析和优化

webpack分析工具:webpack-bundle-analyzer 1. 通过<script src="./vue.js"></script>方式引入vue、vuex、vue-router等包(CDN) // webpack.config.jsif(process.env.NODE_ENV==='production') {module.exports = {devtool: 'none

Java中的大数据处理与分析架构

Java中的大数据处理与分析架构 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们来讨论Java中的大数据处理与分析架构。随着大数据时代的到来,海量数据的存储、处理和分析变得至关重要。Java作为一门广泛使用的编程语言,在大数据领域有着广泛的应用。本文将介绍Java在大数据处理和分析中的关键技术和架构设计。 大数据处理与