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

相关文章

MySQL中的MVCC底层原理解读

《MySQL中的MVCC底层原理解读》本文详细介绍了MySQL中的多版本并发控制(MVCC)机制,包括版本链、ReadView以及在不同事务隔离级别下MVCC的工作原理,通过一个具体的示例演示了在可重... 目录简介ReadView版本链演示过程总结简介MVCC(Multi-Version Concurr

关于Gateway路由匹配规则解读

《关于Gateway路由匹配规则解读》本文详细介绍了SpringCloudGateway的路由匹配规则,包括基本概念、常用属性、实际应用以及注意事项,路由匹配规则决定了请求如何被转发到目标服务,是Ga... 目录Gateway路由匹配规则一、基本概念二、常用属性三、实际应用四、注意事项总结Gateway路由

解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)

《解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)》该文章介绍了使用Redis的阻塞队列和Stream流的消息队列来优化秒杀系统的方案,通过将秒杀流程拆分为两条流水线,使用Redi... 目录Redis秒杀优化方案(阻塞队列+Stream流的消息队列)什么是消息队列?消费者组的工作方式每

解读静态资源访问static-locations和static-path-pattern

《解读静态资源访问static-locations和static-path-pattern》本文主要介绍了SpringBoot中静态资源的配置和访问方式,包括静态资源的默认前缀、默认地址、目录结构、访... 目录静态资源访问static-locations和static-path-pattern静态资源配置

MySQL中时区参数time_zone解读

《MySQL中时区参数time_zone解读》MySQL时区参数time_zone用于控制系统函数和字段的DEFAULTCURRENT_TIMESTAMP属性,修改时区可能会影响timestamp类型... 目录前言1.时区参数影响2.如何设置3.字段类型选择总结前言mysql 时区参数 time_zon

MySQL中的锁和MVCC机制解读

《MySQL中的锁和MVCC机制解读》MySQL事务、锁和MVCC机制是确保数据库操作原子性、一致性和隔离性的关键,事务必须遵循ACID原则,锁的类型包括表级锁、行级锁和意向锁,MVCC通过非锁定读和... 目录mysql的锁和MVCC机制事务的概念与ACID特性锁的类型及其工作机制锁的粒度与性能影响多版本

Redis过期键删除策略解读

《Redis过期键删除策略解读》Redis通过惰性删除策略和定期删除策略来管理过期键,惰性删除策略在键被访问时检查是否过期并删除,节省CPU开销但可能导致过期键滞留,定期删除策略定期扫描并删除过期键,... 目录1.Redis使用两种不同的策略来删除过期键,分别是惰性删除策略和定期删除策略1.1惰性删除策略

Redis与缓存解读

《Redis与缓存解读》文章介绍了Redis作为缓存层的优势和缺点,并分析了六种缓存更新策略,包括超时剔除、先删缓存再更新数据库、旁路缓存、先更新数据库再删缓存、先更新数据库再更新缓存、读写穿透和异步... 目录缓存缓存优缺点缓存更新策略超时剔除先删缓存再更新数据库旁路缓存(先更新数据库,再删缓存)先更新数

C#反射编程之GetConstructor()方法解读

《C#反射编程之GetConstructor()方法解读》C#中Type类的GetConstructor()方法用于获取指定类型的构造函数,该方法有多个重载版本,可以根据不同的参数获取不同特性的构造函... 目录C# GetConstructor()方法有4个重载以GetConstructor(Type[]

MCU7.keil中build产生的hex文件解读

1.hex文件大致解读 闲来无事,查看了MCU6.用keil新建项目的hex文件 用FlexHex打开 给我的第一印象是:经过软件的解释之后,发现这些数据排列地十分整齐 :02000F0080FE71:03000000020003F8:0C000300787FE4F6D8FD75810702000F3D:00000001FF 把解释后的数据当作十六进制来观察 1.每一行数据