LayoutInflater.inflate()用法

来源:互联网 发布:易语言写mysql数据库 编辑:程序博客网 时间:2024/05/04 13:22

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);  }  
0 0