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

相关文章

C#之List集合去重复对象的实现方法

《C#之List集合去重复对象的实现方法》:本文主要介绍C#之List集合去重复对象的实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C# List集合去重复对象方法1、测试数据2、测试数据3、知识点补充总结C# List集合去重复对象方法1、测试数据

SpringBoot读取ZooKeeper(ZK)属性的方法实现

《SpringBoot读取ZooKeeper(ZK)属性的方法实现》本文主要介绍了SpringBoot读取ZooKeeper(ZK)属性的方法实现,强调使用@ConfigurationProperti... 目录1. 在配置文件中定义 ZK 属性application.propertiesapplicati

Golang 日志处理和正则处理的操作方法

《Golang日志处理和正则处理的操作方法》:本文主要介绍Golang日志处理和正则处理的操作方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录1、logx日志处理1.1、logx简介1.2、日志初始化与配置1.3、常用方法1.4、配合defer

MyBatis设计SQL返回布尔值(Boolean)的常见方法

《MyBatis设计SQL返回布尔值(Boolean)的常见方法》这篇文章主要为大家详细介绍了MyBatis设计SQL返回布尔值(Boolean)的几种常见方法,文中的示例代码讲解详细,感兴趣的小伙伴... 目录方案一:使用COUNT查询存在性(推荐)方案二:条件表达式直接返回布尔方案三:存在性检查(EXI

Java调用C#动态库的三种方法详解

《Java调用C#动态库的三种方法详解》在这个多语言编程的时代,Java和C#就像两位才华横溢的舞者,各自在不同的舞台上展现着独特的魅力,然而,当它们携手合作时,又会碰撞出怎样绚丽的火花呢?今天,我们... 目录方法1:C++/CLI搭建桥梁——Java ↔ C# 的“翻译官”步骤1:创建C#类库(.NET

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

java String.join()方法实例详解

《javaString.join()方法实例详解》String.join()是Java提供的一个实用方法,用于将多个字符串按照指定的分隔符连接成一个字符串,这一方法是Java8中引入的,极大地简化了... 目录bVARxMJava String.join() 方法详解1. 方法定义2. 基本用法2.1 拼接

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4