I tried, in code, to inflate a view into a container and to get at the same time a reference to my inflated View (a Button). So the code was like this:
Button mybut = (Button) getLayoutInflater().inflate(resID, lyMain, true);
But this doesn't work: the returned result is not what I expected. Reading the doc at https://developer.android.com/reference/android/view/LayoutInflater.html, I've found that:
(inflate...returns)... The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.
Now the stupid question: why this method should return something I already know (when I pass a root and "true" to attach to it)? It is more probable that I need a reference to the just inflated View, rather than to the root/container I passed to the method.
The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.
The first parameter points to the layout resource you want to inflate. The second parameter is the root view of the hierarchy you are inflating the resource to attach to. When the third parameter is present, it governs whether or not the inflated view is attached to the supplied root after inflation.
The inflate() function of the Inflater class is used to uncompress the input data and fill the given buffer with the uncompressed data.
"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.
It is indeed odd. But doing the following will have the exact same result, but will actually capture the inflated layout:
Button mybut = (Button) getLayoutInflater().inflate(resID, lyMain, false);
lyMain.addView(mybut);
So it does require an extra line of code, but that seems like a minor inconvenience to me compared to having to call findViewById
or getView(index)
.
The documentation explains the difference fairly well, but I guess you've already read that:
root: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
I think the reason of this design choice is that your layout resource might not have a root itself.
That is the case with <merge>
layouts, e.g.
<merge>
<View />
<Button />
</merge>
This can be inflated in a parent ViewGroup, but can’t be represented as a whole with a single View instance. Returning the parent ViewGroup seems the only choice here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With