关于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

相关文章

Agent开发核心技术解析以及现代Agent架构设计

《Agent开发核心技术解析以及现代Agent架构设计》在人工智能领域,Agent并非一个全新的概念,但在大模型时代,它被赋予了全新的生命力,简单来说,Agent是一个能够自主感知环境、理解任务、制定... 目录一、回归本源:到底什么是Agent?二、核心链路拆解:Agent的"大脑"与"四肢"1. 规划模

检查 Nginx 是否启动的几种方法

《检查Nginx是否启动的几种方法》本文主要介绍了检查Nginx是否启动的几种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1. 使用 systemctl 命令(推荐)2. 使用 service 命令3. 检查进程是否存在4

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

MySQL字符串转数值的方法全解析

《MySQL字符串转数值的方法全解析》在MySQL开发中,字符串与数值的转换是高频操作,本文从隐式转换原理、显式转换方法、典型场景案例、风险防控四个维度系统梳理,助您精准掌握这一核心技能,需要的朋友可... 目录一、隐式转换:自动但需警惕的&ld编程quo;双刃剑”二、显式转换:三大核心方法详解三、典型场景

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE

Python中4大日志记录库比较的终极PK

《Python中4大日志记录库比较的终极PK》日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程,:本文主要介绍Python中4大日志记录库比较的相关资料,文中通过代码介绍的非常详细,... 目录一、logging库1、优点2、缺点二、LogAid库三、Loguru库四、Structlogphp

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

springboot中配置logback-spring.xml的方法

《springboot中配置logback-spring.xml的方法》文章介绍了如何在SpringBoot项目中配置logback-spring.xml文件来进行日志管理,包括如何定义日志输出方式、... 目录一、在src/main/resources目录下,也就是在classpath路径下创建logba

SQL Server中行转列方法详细讲解

《SQLServer中行转列方法详细讲解》SQL行转列、列转行可以帮助我们更方便地处理数据,生成需要的报表和结果集,:本文主要介绍SQLServer中行转列方法的相关资料,需要的朋友可以参考下... 目录前言一、为什么需要行转列二、行转列的基本概念三、使用PIVOT运算符进行行转列1.创建示例数据表并插入数

C++打印 vector的几种方法小结

《C++打印vector的几种方法小结》本文介绍了C++中遍历vector的几种方法,包括使用迭代器、auto关键字、typedef、计数器以及C++11引入的范围基础循环,具有一定的参考价值,感兴... 目录1. 使用迭代器2. 使用 auto (C++11) / typedef / type alias