LayoutInflater.inflate()用法

本文详细介绍了LayoutInflater的三种获取方式及其inflate方法的使用,包括方法参数resource、root及attachToRoot的作用,并给出了具体的使用场景建议。

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

1.获取方式:

LayoutInflater inflater=LayoutInflater.from(this);//第一种

LayoutInflater inflater=getLayoutInflater();      //第二种

LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);//第三种

2.方法参数

LayoutInflater.from(mContext).inflate(int resource, ViewGroup root, boolean attachToRoot);

resource:需要加载布局文件的id,意思是需要将这个布局文件中加载到Activity或者是自定义View中来操作。

root:需要附加到resource资源文件的根控件

attachToRoot:是否将root附加到布局文件的根视图上

  1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
  2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
  3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
  4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

最后注意两点:
1.RecylerView中一定要用LayoutInflater.inflate()方法,当然也能用View.inflate()只不过布局的属性就没有了,不能达到你想要的效果。

2.强烈建议 加载布局都用LayoutInflater.inflate(),因为看源码View.inflate()内部也是调用LayoutInflater.inflate()的,源码如下:

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {  
    LayoutInflater factory = LayoutInflater.from(context);  
    return factory.inflate(resource, root);  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值