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

相关文章

Nacos注册中心和配置中心的底层原理全面解读

《Nacos注册中心和配置中心的底层原理全面解读》:本文主要介绍Nacos注册中心和配置中心的底层原理的全面解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录临时实例和永久实例为什么 Nacos 要将服务实例分为临时实例和永久实例?1.x 版本和2.x版本的区别

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

C++类和对象之默认成员函数的使用解读

《C++类和对象之默认成员函数的使用解读》:本文主要介绍C++类和对象之默认成员函数的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、默认成员函数有哪些二、各默认成员函数详解默认构造函数析构函数拷贝构造函数拷贝赋值运算符三、默认成员函数的注意事项总结一

MySQL的ALTER TABLE命令的使用解读

《MySQL的ALTERTABLE命令的使用解读》:本文主要介绍MySQL的ALTERTABLE命令的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、查看所建表的编China编程码格式2、修改表的编码格式3、修改列队数据类型4、添加列5、修改列的位置5.1、把列

Linux CPU飙升排查五步法解读

《LinuxCPU飙升排查五步法解读》:本文主要介绍LinuxCPU飙升排查五步法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录排查思路-五步法1. top命令定位应用进程pid2.php top-Hp[pid]定位应用进程对应的线程tid3. printf"%

解读@ConfigurationProperties和@value的区别

《解读@ConfigurationProperties和@value的区别》:本文主要介绍@ConfigurationProperties和@value的区别及说明,具有很好的参考价值,希望对大家... 目录1. 功能对比2. 使用场景对比@ConfigurationProperties@Value3. 核

Jupyter notebook安装步骤解读

《Jupyternotebook安装步骤解读》:本文主要介绍Jupyternotebook安装步骤,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、开始安装二、更改打开文件位置和快捷启动方式总结在安装Jupyter notebook 之前,确认您已安装pytho

Java中的StringUtils.isBlank()方法解读

《Java中的StringUtils.isBlank()方法解读》:本文主要介绍Java中的StringUtils.isBlank()方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录所在库及依赖引入方法签名方法功能示例代码代码解释与其他方法的对比总结StringUtils.isBl

对Django中时区的解读

《对Django中时区的解读》:本文主要介绍对Django中时区的解读方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景前端数据库中存储接口返回AI的解释问题:这样设置的作用答案获取当前时间(自动带时区)转换为北京时间显示总结背景设置时区为北京时间 TIM

Java中的内部类和常用类用法解读

《Java中的内部类和常用类用法解读》:本文主要介绍Java中的内部类和常用类用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录内部类和常用类内部类成员内部类静态内部类局部内部类匿名内部类常用类Object类包装类String类StringBuffer和Stri