关于inflate的几个方法解析(结合日志源码)

2023-11-25 04:58

本文主要是介绍关于inflate的几个方法解析(结合日志源码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

inflate使我们使用频率极高的api了,并且他有多个重载的方法,如下:
View inflate(int, ViewGroup)   
View inflate(XmlPullParser, ViewGroup)   
View inflate(int, ViewGroup, boolean)   
View inflate(XmlPullParser, ViewGroup, boolean)
我们要在不同的使用场景下,进行介绍。
  1. 我们一般不使用传入XmlPullParser解析器的方法,一般都是直接传入XML文件,方法内部会将XML转换成解析器,代码如下:
    final XmlResourceParser parser = res.getLayout(resource);
  1. 剩余的两个方法主要是最后一个参数(attachToRoot)是否传入的区别,其实两个参数的方法,最终会调用到三个参数的方法,代码如下:
 public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {return inflate(parser, root, root != null);}

只不过最后一个参数是根据root是否为null来决定的,这也比较好理解,如果你没有传入root本身就没有父view可绑定,所以attachToRoot自然是false

  1. 介绍View inflate(int, ViewGroup) 方法,第二个参数是否传入null,所产生的不同的结果。

    1. Fragment中使用,在onCreateView中
     @Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LogUtils.d("-----"+container.toString());View inflate = inflater.inflate(R.layout.fragment, container);return inflate;}//如上使用会报错:Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.//因为container不为null,原因是创建Fragment的时候,系统会默认给Fragment添加一个FrameLayout的父布局,如果这个时候在把Fragment加入到Activity中的布局时,就会报错了//打印的日志也证明上面的说法   09-26 04:36:16.725 350-350/test.juyoufuli.com.testapplication D/TestApplication: -----android.widget.FrameLayout{774b98b V.E..... ......ID 0,0-0,0 #7f070041 app:id/fl}

    如何正确使用呢? 两种方案:

        View inflate = inflater.inflate(R.layout.fragment, null);View inflate = inflater.inflate(R.layout.fragment, container,false);//根据源码可知,root传入null和attachToRoot传入false等价
    
    1. 其他常规用法基本原则是不变的,如下面代码:
            FrameLayout viewById = findViewById(R.id.fl);View inflate = getLayoutInflater().inflate(R.layout.fragment,null);LogUtils.d("-----"+inflate.getParent().toString());viewById.addView(inflate);//如上代码空指针错误,inflate.getParent()为null,常规填充是不会有父view的。
    
  2. 继续介绍传入不同的第三个参数,view会有不同的显示效果,源码的中的关键代码:

    /*** @param root Optional view to be the parent of the generated hierarchy (if* <em>attachToRoot</em> is true), or else simply an object that* provides a set of LayoutParams values for root of the returned*hierarchy (if <em>attachToRoot</em> is false.)*/ 
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 {//主要部分if (TAG_MERGE.equals(name)) {//如果root为null或者不绑定到root,则布局效果都是按照父view的来的rInflate(parser, root, inflaterContext, attrs, false);} else {// Temp is the root view that was found in the xml// 这个传入的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);//初始化出来的子view不绑定到root上,则设置指定父布局的参数(算是一组参考的布局参数),后续需要自己调用addview方法,并且并不一定必须add到这个布局上if (!attachToRoot) {// Set the layout params for temp if we are not// attaching. (If we are, we use addView, below)temp.setLayoutParams(params);}}// Inflate all children under temp against its context.rInflateChildren(parser, temp, attrs, true);// We are supposed to attach all the views we found (int temp)// to root. Do that now.//如果绑定到root上的话,就直接通过addview来加入到root的布局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.// 未指定父布局或者不绑定的话直接返回解析好viewif (root == null || !attachToRoot) {result = 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;}}

上面的注解也还算详细了,如有问题望各位大佬指点。

如上基本完成分析,下面总结一下使用的注意事项。
  1. 在绑定view的时候要注意是inflate出来的view已经默认添加了父view
  2. 如果还不确定要添加到的view,直接传入null即可,会减少一些计算逻辑
  3. 如果attachToRoot传入true,则不可以在调用addview方法,将该view添加到其他view上

这篇关于关于inflate的几个方法解析(结合日志源码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

全面解析Golang 中的 Gorilla CORS 中间件正确用法

《全面解析Golang中的GorillaCORS中间件正确用法》Golang中使用gorilla/mux路由器配合rs/cors中间件库可以优雅地解决这个问题,然而,很多人刚开始使用时会遇到配... 目录如何让 golang 中的 Gorilla CORS 中间件正确工作一、基础依赖二、错误用法(很多人一开

Mysql中设计数据表的过程解析

《Mysql中设计数据表的过程解析》数据库约束通过NOTNULL、UNIQUE、DEFAULT、主键和外键等规则保障数据完整性,自动校验数据,减少人工错误,提升数据一致性和业务逻辑严谨性,本文介绍My... 目录1.引言2.NOT NULL——制定某列不可以存储NULL值2.UNIQUE——保证某一列的每一

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方

SQL Server安装时候没有中文选项的解决方法

《SQLServer安装时候没有中文选项的解决方法》用户安装SQLServer时界面全英文,无中文选项,通过修改安装设置中的国家或地区为中文中国,重启安装程序后界面恢复中文,解决了问题,对SQLSe... 你是不是在安装SQL Server时候发现安装界面和别人不同,并且无论如何都没有中文选项?这个问题也

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

MySQL CTE (Common Table Expressions)示例全解析

《MySQLCTE(CommonTableExpressions)示例全解析》MySQL8.0引入CTE,支持递归查询,可创建临时命名结果集,提升复杂查询的可读性与维护性,适用于层次结构数据处... 目录基本语法CTE 主要特点非递归 CTE简单 CTE 示例多 CTE 示例递归 CTE基本递归 CTE 结

Spring Boot 3.x 中 WebClient 示例详解析

《SpringBoot3.x中WebClient示例详解析》SpringBoot3.x中WebClient是响应式HTTP客户端,替代RestTemplate,支持异步非阻塞请求,涵盖GET... 目录Spring Boot 3.x 中 WebClient 全面详解及示例1. WebClient 简介2.

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

Spring Boot从main方法到内嵌Tomcat的全过程(自动化流程)

《SpringBoot从main方法到内嵌Tomcat的全过程(自动化流程)》SpringBoot启动始于main方法,创建SpringApplication实例,初始化上下文,准备环境,刷新容器并... 目录1. 入口:main方法2. SpringApplication初始化2.1 构造阶段3. 运行阶