LayoutInflater.inflate()参数用法及导致适配器布局宽度高度错乱问题

这个LayoutInflater.inflate()应该用的都挺频繁的,比如你的fragment,你的适配器里面都会有用到。但它的参数的意义你都理解嘛? 有没有遇到过这样一个问题?你的适配器宽度明明设置了全部但是实际上却没有,布局错乱了,然后你苦寻无果,最后你直接在代码中动态重新设置了一次宽度,获取屏幕的宽度在代码中动态直接设置。 今天我们就来解释一下这个LayoutInflater.inflate()和上面的问题。

LayoutInflater.inflate()方法你可以传三个参数也可以参俩个参数,但意义就不同,这就需要你判断你需要哪种。 三个参数方法

1 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { 2 final Resources res = getContext().getResources(); 3 if (DEBUG) { 4 Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" (" 5 + Integer.toHexString(resource) + ")"); 6 } 7 8 final XmlResourceParser parser = res.getLayout(resource); 9 try { 10 return inflate(parser, root, attachToRoot); 11 } finally { 12 parser.close(); 13 } 14 }

二个参数方法 其实只是它帮你传了一个本质上都是调的同一个。

1public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { 2 return inflate(resource, root, root != null); 3 }

我们来围绕源码说一说(上述源码是28),进去inflate方法以后主要是解析一下xml,然后再调用了一次inflate方法

1return inflate(parser, root, attachToRoot);

这次的inflate方法就比较关键,你想知道的答案都在这里

1 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { 2 synchronized (mConstructorArgs) { 3 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate"); 4 5 final Context inflaterContext = mContext; 6 final AttributeSet attrs = Xml.asAttributeSet(parser); 7 Context lastContext = (Context) mConstructorArgs[0]; 8 mConstructorArgs[0] = inflaterContext; 9 View result = root; 10 11 try { 12 // Look for the root node. 13 int type; 14 while ((type = parser.next()) != XmlPullParser.START_TAG && 15 type != XmlPullParser.END_DOCUMENT) { 16 // Empty 17 } 18 19 if (type != XmlPullParser.START_TAG) { 20 throw new InflateException(parser.getPositionDescription() 21 + ": No start tag found!"); 22 } 23 24 final String name = parser.getName(); 25 26 if (DEBUG) { 27 System.out.println("**************************"); 28 System.out.println("Creating root view: " 29 + name); 30 System.out.println("**************************"); 31 } 32 33 if (TAG_MERGE.equals(name)) { 34 //注意这里 当root为null并且attachToRoot为false的时候直接抛出异常,所以当我们的root为null的时候我们的attachToroot应该也为null,接着往下看 35 if (root == null || !attachToRoot) { 36 throw new InflateException("<merge /> can be used only with a valid " 37 + "ViewGroup root and attachToRoot=true"); 38 } 39 40 rInflate(parser, root, inflaterContext, attrs, false); 41 } else { 42 // Temp is the root view that was found in the xml 43 //Temp是在xml中找到的根视图,根布局拿到了,接着看 44 final View temp = createViewFromTag(root, name, inflaterContext, attrs); 45 46 ViewGroup.LayoutParams params = null; 47 48//当root不为空 49 if (root != null) { 50 if (DEBUG) { 51 System.out.println("Creating params from root: " + 52 root); 53 } 54 // Create layout params that match root, if supplied 55 //创建匹配根目录的布局参数,取到我们布局的信息,接着看 56 params = root.generateLayoutParams(attrs); 57 //划重点,如果第三个参数为false我们就把temp设置好布局信息 58 if (!attachToRoot) { 59 // Set the layout params for temp if we are not 60 // attaching. (If we are, we use addView, below) 61 temp.setLayoutParams(params); 62 } 63 } 64 65 if (DEBUG) { 66 System.out.println("-----> start inflating children"); 67 } 68 69 // Inflate all children under temp against its context. 70 //根据上下文对temp下的所有儿童进行充气。 71 //通俗来说我们上面弄了一个temp根布局,所以闲着我们再把我们第一个参数中的布局全都添加到temp中。接着看 72 rInflateChildren(parser, temp, attrs, true); 73 74 if (DEBUG) { 75 System.out.println("-----> done inflating children"); 76 } 77 78 // We are supposed to attach all the views we found (int temp) 79 // to root. Do that now. 80 //这里划重点了,这里当root不为空,第三个参数为true的时候,就是root添加temp布局,就相当于我们把第一个参数添加到了第二个参数中,然后返回,接着看 81 if (root != null && attachToRoot) { 82 root.addView(temp, params); 83 } 84 85 // Decide whether to return the root that was passed in or the 86 // top view found in xml. 87 //划重点,这里只要我们第三个参数为false或者第二个参数为空的时候就会走这里,这里是没什么区别的,但根据上面一个判断我们就知道这里最终返回的数据会收到第三个参数的影响,最终这个会结合上面的判单影响到我们宽高,导致布局错乱。 88 if (root == null || !attachToRoot) { 89 result = temp; 90 } 91 } 92 93 } catch (XmlPullParserException e) { 94 final InflateException ie = new InflateException(e.getMessage(), e); 95 ie.setStackTrace(EMPTY_STACK_TRACE); 96 throw ie; 97 } catch (Exception e) { 98 final InflateException ie = new InflateException(parser.getPositionDescription() 99 + ": " + e.getMessage(), e); 100 ie.setStackTrace(EMPTY_STACK_TRACE); 101 throw ie; 102 } finally { 103 // Don't retain static reference on context. 104 mConstructorArgs[0] = lastContext; 105 mConstructorArgs[1] = null; 106 107 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 108 } 109 110 return result; 111 } 112 }

如上我们已经把关键源码都过了一遍,最后再总结一次, 参数为 (layout1,layout2,true)的时候就是把layout1添加到layout2 参数为 (layout1,layout2,false) 的时候就是layout2辅助layout1生成根布局信息 参数为 (layout1,null) 的时候就直接返回了一个布局,没有生成布局信息

那么现在我们来说第二问题,适配器布局错乱的,我把关键代码提出来了,如果你适配器设置了 (layout,null) 这样就会导致布局错乱,原因看代码咯。所以应该改成 (layout1,layout2,false)即可。

1 if (!attachToRoot) { 2 temp.setLayoutParams(params); 3 } 4 if (root == null || !attachToRoot) { 5 result = temp; 6 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

​一篇文章总结一下Python库中关于时间的常见操作

前言本次来总结一下关于Python时间的相关操作,有一个有趣的问题。如果你的业务用不到时间相关的操作,你的业务基本上会一直用不到。但是如果你的业务一旦用到了时间操作,你就会发现,淦,到处都是时间操作。。。所以思来想去,还是总结一下吧,本次会采用类型注解方式。time包importtime时间戳从1970年1月1日00:00:00标准时区诞生到现在

Twitter的分布式自增ID算法snowflake (Java版)

概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移