LayoutInflater中inflate()参数解析

LayoutInflater是用来动态加载XML布局文件的工具,inflate方法主要通过解析XML生成View对象。当root为null时,attachToRoot参数无效;若root不为null,attachToRoot=true会自动添加到父布局,而false则需要手动添加。View.inflate与LayoutInflater.inflate的区别在于前者默认使用自身作为父视图,后者可自定义父视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、关于LayoutInflater,它是如何通过 inflate 方法获取到具体View的?

获得LayoutInflater实例的方式有以下三种:

LayoutInflater inflater = getLayoutInflater();

LayoutInflater inflater = LayoutInflater.from(this);

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

有两个方法重载可以实现:

layoutInflater.inflate(int ResourceId,ViewGroup root)
layoutInflater.inflate(int ResourceId,ViewGroup root,boolean attachToRoot )

LayoutInflater.inflate() 原理分析

2、inflate()三个参数的

LayoutInflater.inflate(int ResourceId,ViewGroup root,boolean attachToRoot )

LayoutInflater中inflate()参数解析

  • 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

若第二个参数为null,也就是我们不指定父控件,那么新生产的view对象的根布局的某些参数会失效,比如Layout_width和Layout_height会失效

 val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,null,false)
或者   val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,null,true)
 //将获取到View对象,添加到container布局中
 container.addView(view) // 这时,inflate_layout布局中最外层的  layout相关的属性  都无效。
  • 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
    程序内部自动调用了addview(),将该View添加到父布局中;所以不能再次手动调用addview()
 val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,container,true)
  • 如果root不为null,attachToRoot设为false,该view不会被添加到父view当中;但是可以手动调用addview()。
 val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,container,false)
 //将获取到View对象,添加到container布局中
 container.addView(view)

在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

3、View.inflate和LayoutInflater.inflate的区别?

https://www.cnblogs.com/baipengzhan/p/LayoutInflater_inflate_View_inflate.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值