Question:
Can someone clearly explain the essence of the parameters of the inflater.inflate(int resource, ViewGroup root, boolean attachToRoot)
? With the first it seems clear, it is, in fact, converted from XML into a full-fledged object. According to the second and third, it’s dryly written that one is the parent element (it’s not entirely clear what the parent element is), and the second is responsible for attaching this element to the parent or something.
Answer:
Here is a great Anglo-Saxon article: Understanding Android's LayoutInflater.inflate()
Brief extract:
-
LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)
– 1 argument specifying which layout file to load. The second one is the parent element of the markup, to which the loaded markup will be automatically added if the 3 parameter istrue
or from where theLayoutParams
for the loaded view will be taken ifattachToRoot
false
-
From point 1 it follows that the following lines do the same thing:
//загружаем файл разметки и вручную добавляем его в контейнер
View v = inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(v);
//загружаем файл разметки и автоматически добавляем его в контейнер
inflater.inflate(R.layout.custom_button, mLinearLayout, true);
//загружаем файл разметки и автоматически добавляем его в контейнер
inflater.inflate(R.layout.custom_button, mLinearLayout);
-
In some cases, the system itself adds the loaded view to the container and does not need to interfere with it. Examples are loading the markup for a fragment and for a list cell (
ListView
,RecyclerView
,GridView
etc). In these cases, it is mandatory to passfalse
the last argument. The system itself will determine at what point the markup will need to be added to the parent container -
In some cases, it makes no sense to pass a second argument, because it's like he doesn't exist. This is a case of custom dialog markup. In this case, you can pass
null
instead of the parent element of the markup to load. -
In some cases, the
<merge>
tag is used as the root tag in the markup file. Such views cannot be placed in a variable, they can only be placed directly in the markup. There is no way to do without passingtrue
as the last parameter. This can be useful if you want to be able to, for example, add 2 buttons defined in the same markup file to different containers. For example, in the sameLinearLayout
but with a different orientation of the latter.