What does the LayoutInflater attachToRoot parameter mean?

Jeff Axelrod picture Jeff Axelrod · Sep 24, 2012 · Viewed 60.6k times · Source

The LayoutInflater.inflate documentation isn't exactly clear to me about the purpose of the attachToRoot parameter.

attachToRoot: whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

Could someone please explain in more detail, specifically what the root view is, and maybe show an example of a change in behavior between true and false values?

Answer

Rohit Singh picture Rohit Singh · Aug 22, 2017

NOW OR NOT NOW

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 parent. WRONG
In both cases, child view will be added to parentView. It is just the matter of time.

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

public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle bundle)
  {
        super.onCreateView(inflater,parent,bundle);
        View view = inflater.inflate(R.layout.image_fragment,parent,false);
        .....
        return view;
  }

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

getSupportFragmentManager()
      .beginTransaction()
      .add(parent, childFragment)
      .commit();

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.