LayoutInflater.inflate全面解读

2024-01-27 10:36

本文主要是介绍LayoutInflater.inflate全面解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

方法解析

LayoutInflater.inflate() 是 Android 系统中用于将 XML 布局文件转换成相应的 View 的方法。在 Android 开发中,我们经常使用此方法来动态创建和填充布局。

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
或者
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)

参数含义:

  1. int resource: 这是要加载的 XML 布局资源 ID;

  2. ViewGroup root: 可选的 ViewGroup 参数,它作为新创建View的父容器。如果提供了父容器,inflate 过程会考虑父容器的 LayoutParams,并可能根据需要调整新创建视图的属性;

  3. boolean attachToRoot: 是否应将新创建的View立即附加到提供的父容器中。如果为 true,则新生成的视图层次结构会立即添加到父容器内;反之则不会立即附加,但可以手动添加。

inflate两个参数的方法内部调用了三个参数的方法,有如容器就把生成的View添加到父容器中,反之就不添加。
在这里插入图片描述
以下示例演示以三个参数来演示

示例

创建一个简单的Activity来演示,activity_main是一个ConstraintLayout布局,宽高都是match_parent,背景颜色是绿色
item_test是要inflate的布局,宽高分别是300dp和100dp,颜色是蓝色,在约束布局中居中显示

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/cl_container"android:background="@color/design_default_color_secondary_variant"tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="300dp"xmlns:app="http://schemas.android.com/apk/res-auto"android:background="@color/design_default_color_primary"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toBottomOf="parent"android:layout_height="100dp"></LinearLayout>

root不为null,attachToRoot为true

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)val view = LayoutInflater.from(this).inflate(R.layout.item_test, clContainer, true)}
}

效果:view在父容器中居中显示
在这里插入图片描述

root不为null,attachToRoot为false

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)val view = LayoutInflater.from(this).inflate(R.layout.item_test, clContainer, false)}
}

效果:view未添加到父容器clContainer中
在这里插入图片描述
手动添加View

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)val view = LayoutInflater.from(this).inflate(R.layout.item_test, clContainer, false)clContainer.addView(view)}
}

效果:view被手动添加到父容器clContainer,居中显示
在这里插入图片描述

root为null

root为null,attachToRoot参数已经没有意义了,所以不用考虑

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)val view = LayoutInflater.from(this).inflate(R.layout.item_test, null, false)clContainer.addView(view)}
}

效果:为什么不显示item_test的蓝色方块呢?因为root为null,inflate 过程会不能参照父容器的 LayoutParams来进行了,也就是,所以无法生成相应的布局参数,宽高属性会失效。
在这里插入图片描述
如果我们在item_test布局里添加一个Image,会发现布局会包裹ImageView,因为ImageView会处于容器LinearLayout中ImageView宽高有效

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="300dp"xmlns:app="http://schemas.android.com/apk/res-auto"android:background="@color/design_default_color_primary"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toBottomOf="parent"android:layout_height="100dp"><ImageViewandroid:src="@mipmap/ic_launcher"android:layout_width="60dp"android:layout_height="60dp"/>
</LinearLayout>

在这里插入图片描述

关于The specified child already has a parent异常

众所周知,Android中每个View只能有一个父View,如果需要再一个新的父View中使用该View,需要先把该View在当前的父View中删除才行。

如果inflate已经帮我们将View添加到父容器了,我们又手动addView了,该View机会有两个父View。所以会出现 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first。

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)val view = LayoutInflater.from(this).inflate(R.layout.item_test, clContainer, true)clContainer.addView(view)}
}

源码分析

我们从常见的ListView场景来分析

public class ListAdapter extends ArrayAdapter<String> {private int mrescourceId;public ListAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {super(context, resource, objects);this.mrescourceId = resource;}@NonNull@Overridepublic View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {String item = getItem(position);View view = LayoutInflater.from(getContext()).inflate(mrescourceId, parent, false);TextView textView = view.findViewById(R.id.tv_item_name);textView.setText(item);return view;}
}

布局文件中假设我想让item的宽度是100dp,那我设置根布局ConstraintLayout宽度是100dp

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="100dp"android:layout_height="match_parent"xmlns:app="http://schemas.android.com/apk/res-auto"><TextViewandroid:background="@color/colorAccent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintLeft_toLeftOf="parent"android:id="@+id/tv_item_name"android:layout_width="match_parent"android:layout_height="60dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

布局效果
在这里插入图片描述
运行效果
在这里插入图片描述
运行效果和我们设置的一样。那如果我将inflate的第二个参数改为null会有什么效果
在这里插入图片描述
在这里插入图片描述
item的高度包裹内容,没问题,宽度竟然占满全屏了?为什么宽度不是包裹内容呢?
来看源码:

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {…………synchronized (mConstructorArgs) {…………try {final String name = parser.getName();…………if (TAG_MERGE.equals(name)) {…………} else {// Temp is the root view that was found in the xmlfinal View temp = createViewFromTag(root, name, inflaterContext, attrs);ViewGroup.LayoutParams params = null;if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// 当root!=null且attachToRoot=false的时候,//获取了布局文件的布局参数,然后设置给了创建好的Viewparams = root.generateLayoutParams(attrs);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.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.if (root == null || !attachToRoot) {result = temp;}}} catch (XmlPullParserException e) {…………} catch (Exception e) {…………} finally {…………}return result;}}

当我们调用inflate方法后,将会把布局文件传入XmlPullParser,然后调用上面的方法,root和attachToRoot分别是传入的null和false。

createViewFromTag

首先注意上面方法中的createViewFromTag,它的作用是反射调用根布局View的2个参数的构造方法,来创建View。
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

root.generateLayoutParams(attrs)

在inflate方法源码中我们看到,当root!=null的时候,获取了布局文件的布局参数,然后设置给了创建好的View
在这里插入图片描述
看到这里,基本可以明白为什么第一次root传parent且attachToRoot=false的时候,设置的100dp是有效的了,因为创建完ConstraintLayout之后立即给其设置了布局参数LayoutParams

那为什么root=null且attachToRoot=false的时候,列表的item是充满屏幕的呢?

由于View是在Adapter中创建的,肯定不是创建时造成的,因为上面View的创建过程已经分析了。

那么首先想到的是哪里用到这个View,adapter肯定是在ListView或者RecyclerView中使用,由于我的demo中使用的是ArrayAdapter搭配ListView,那看下ListView的代码
查看ListView中哪里用到getView方法了:
在这里插入图片描述
我们查看setItemViewLayoutParams方法
在这里插入图片描述
上面方法中,由于adapter在创建view的过程中root = null,所创建的View没有设置布局参数所以走generateDefaultLayoutParams方法

查看generateDefaultLayoutParams方法
在这里插入图片描述
创建了一个宽是ViewGroup.LayoutParams.MATCH_PARENT
高是ViewGroup.LayoutParams.WRAP_CONTENT的布局参数。

然后在setItemViewLayoutParams方法中通过child.setLayoutParams(lp);设置给了item的根布局,最终造成了item的宽度不是100dp而是占满全屏。
而且item的高度其实也是包裹内容的,只是我设置了TextView的高度是60dp。

这篇关于LayoutInflater.inflate全面解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python 字符串裁切与提取全面且实用的解决方案

《Python字符串裁切与提取全面且实用的解决方案》本文梳理了Python字符串处理方法,涵盖基础切片、split/partition分割、正则匹配及结构化数据解析(如BeautifulSoup、j... 目录python 字符串裁切与提取的完整指南 基础切片方法1. 使用切片操作符[start:end]2

SpringBoot加载profile全面解析

《SpringBoot加载profile全面解析》SpringBoot的Profile机制通过多配置文件和注解实现环境隔离,支持开发、测试、生产等不同环境的灵活配置切换,无需修改代码,关键点包括配置文... 目录题目详细答案什么是 Profile配置 Profile使用application-{profil

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

C语言自定义类型之联合和枚举解读

《C语言自定义类型之联合和枚举解读》联合体共享内存,大小由最大成员决定,遵循对齐规则;枚举类型列举可能值,提升可读性和类型安全性,两者在C语言中用于优化内存和程序效率... 目录一、联合体1.1 联合体类型的声明1.2 联合体的特点1.2.1 特点11.2.2 特点21.2.3 特点31.3 联合体的大小1

Python标准库datetime模块日期和时间数据类型解读

《Python标准库datetime模块日期和时间数据类型解读》文章介绍Python中datetime模块的date、time、datetime类,用于处理日期、时间及日期时间结合体,通过属性获取时间... 目录Datetime常用类日期date类型使用时间 time 类型使用日期和时间的结合体–日期时间(

C语言中%zu的用法解读

《C语言中%zu的用法解读》size_t是无符号整数类型,用于表示对象大小或内存操作结果,%zu是C99标准中专为size_t设计的printf占位符,避免因类型不匹配导致错误,使用%u或%d可能引发... 目录size_t 类型与 %zu 占位符%zu 的用途替代占位符的风险兼容性说明其他相关占位符验证示

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

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

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

Linux系统之lvcreate命令使用解读

《Linux系统之lvcreate命令使用解读》lvcreate是LVM中创建逻辑卷的核心命令,支持线性、条带化、RAID、镜像、快照、瘦池和缓存池等多种类型,实现灵活存储资源管理,需注意空间分配、R... 目录lvcreate命令详解一、命令概述二、语法格式三、核心功能四、选项详解五、使用示例1. 创建逻

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima