Why LayoutInflater.inflate returns the root passed as parameter?

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.

Upvotes: 10

Views: 1931

Answers (2)

natario
natario

Reputation: 25194

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.

Upvotes: 3

code_mc
code_mc

Reputation: 171

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.)

Upvotes: 6

Related Questions