What does attachToRoot = false in LayoutInflater means in android?

Rohit Singh
2 min readApr 13, 2018

--

This is a re-post of an answer I wrote on Stackoverflow.

The main difference between the “third” parameter attachToRoot being true or false is this.

When you put attachToRoot

true: add the child view to parent RIGHT NOW
false: add the child view to parent NOT NOW.
Add it later. `

When is that later?

That later is when you use, for eg parent.addView(childView)

A common misconception is, if attachToRoot parameter is false then the child view will not be added to the parent. WRONG
In both cases, child view will be added to parentView. It is just a matter of time. In fact,

inflater.inflate(child,parent,false);
parent.addView(child);

is equivalent to

inflater.inflate(child,parent,true);

A BIG NO-NO

You should never pass attachToRoot as true when you are not responsible for adding the child view to parent.
Eg When adding Fragment

if you pass the third parameter true you will get IllegalStateException because of this guy.

Since you have already added the child fragment in onCreateView() by mistake. Calling add will tell you that child view is already added to parent Hence IllegalStateException.
Here you are not responsible for adding childView, FragmentManager is responsible. So always pass false in this case.

NOTE: I have also read that parentView will not get childView touchEvents if attachToRoot is false. But I have not tested it though.

Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.
You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.

--

--

Rohit Singh
Rohit Singh

Written by Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

Responses (1)