LayoutInflater中inflate()参数解析
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