Analysis of inflate() parameter in LayoutInflater

1. Regarding LayoutInflater, how does it obtain a specific View through the inflate method?

There are three ways to obtain a LayoutInflater instance:

LayoutInflater inflater = getLayoutInflater();

LayoutInflater inflater = LayoutInflater.from(this);

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

There are two method overloads to achieve this:

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

LayoutInflater.inflate() principle analysis

2, inflate () three parameters

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

Analysis of inflate() parameter in LayoutInflater

  • If root is null, attachToRoot will have no effect, setting any value is meaningless.

If the second parameter is null, that is, we do not specify the parent control, then some parameters of the root layout of the newly produced view object will be invalid, such as Layout_width and Layout_height will be invalid

 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相关的属性  都无效。
  • If root is not null and attachToRoot is set to true, a parent layout, namely root, will be specified for the loaded layout file.
    The program automatically calls addview() to add the View to the parent layout;So can't manually call addview() again
 val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,container,true)
  • If root is not null and attachToRoot is set to false, the view will not be added to the parent view; but addview() can be called manually.
 val view = LayoutInflater.from(this).inflate(R.layout.inflate_layout,container,false)
 //将获取到View对象,添加到container布局中
 container.addView(view)

If the attachToRoot parameter is not set, if root is not null, the attachToRoot parameter defaults to true.

3. What is the difference between View.inflate and LayoutInflater.inflate?

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

Guess you like

Origin blog.csdn.net/zhijiandedaima/article/details/130679772