What does the LayoutInflater attachToRoot parameter mean? - android

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?

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 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 a 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 the 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 the 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.

If set to true then when your layout is inflated it will be automatically added to the view hierarchy of the ViewGroup specified in the 2nd parameter as a child. For example if the root parameter was a LinearLayout then your inflated view will be automatically added as a child of that view.
If it is set to false then your layout will be inflated but won't be attached to any other layout (so it won't be drawn, receive touch events etc).

Seems like a lot of text in the responses but no code, that's why I decided to revive this old question with a code example, in several responses people mentioned:
If set to true then when your layout is inflated it will be automatically added to the view hierarchy of the ViewGroup specified in the 2nd parameter as a child.
What that actually means in code(what most programmers understand) is:
public class MyCustomLayout extends LinearLayout {
public MyCustomLayout(Context context) {
super(context);
// Inflate the view from the layout resource and pass it as child of mine (Notice I'm a LinearLayout class).
LayoutInflater.from(context).inflate(R.layout.child_view, this, true);
}
}
Notice that previous code is adding the layout R.layout.child_view as child of MyCustomLayout because of attachToRoot param is true and assigns the layout params of the parent exactly in the same way as if I would be using addView programmatically, or as if I did this in xml:
<LinearLayout>
<View.../>
...
</LinearLayout>
The following code explains the scenario when passing attachRoot as false:
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create a stand-alone view
View myView = LayoutInflater.from(context)
.inflate(R.layout.ownRootView, null, false);
linearLayout.addView(myView);
In the previous code you specify that you wanted myView to be it's own root object and do not attach it to any parent, later on we added it as part of the LinearLayout but for a moment it was a stand-alone (no parent) view.
Same thing happens with Fragments, you could add them to an already existing group and be part of it, or just pass the parameters:
inflater.inflate(R.layout.fragment, null, false);
To specify that it will be it's own root.

The documentation and the two previous answers should be enough, just some thoughts from me.
The inflate method is used to inflate layout files. With those inflated layouts you have to possibility to attach them directly to a parent ViewGroup or just inflate the view hierarchy from that layout file and work with it outside of the normal view hierarchy.
In the first case the attachToRoot parameter will have to be set to true(or much simple use the inflate method that takes a layout file and a parent root ViewGroup(non null)). In this case the View returned is simply the ViewGroup that was passed in the method, the ViewGroup to which the inflated view hierarchy will be added.
For the second option the returned View is the root ViewGroup from the layout file. If you remember our last discussion from the include-merge pair question this is one of the reasons for the merge's limitation(when a layout file with merge as root is inflated, you must supply a parent and attachedToRoot must be set to true). If you had a layout file with the root a merge tag and attachedToRoot was set to false then the inflate method will have nothing to return as merge doesn't have an equivalent.
Also, as the documentation says, the inflate version with attachToRoot set to false is important because you can create the view hierarchy with the correct LayoutParams from the parent. This is important in some cases, most notable with the children of AdapterView, a subclass of ViewGroup, for which the addView() methods set is not supported. I'm sure you recall using this line in the getView() method:
convertView = inflater.inflate(R.layout.row_layout, parent, false);
This line ensures that the inflated R.layout.row_layout file has the correct LayoutParams from the AdapterView subclass set on its root ViewGroup. If you wouldn't be doing this you could have some problems with the layout file if the root was a RelativeLayout. The TableLayout/TableRow also have some special and important LayoutParams and you should make sure the views in them have the correct LayoutParams.

I wrote this answer because even after going through several StackOverflow pages I wasn't able to clearly grasp what attachToRoot meant. Below is inflate() method in the LayoutInflater class.
View inflate (int resource, ViewGroup root, boolean attachToRoot)
Take a look at activity_main.xml file, button.xml layout and the MainActivity.java file I created.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
button.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
LinearLayout root = (LinearLayout) findViewById(R.id.root);
View view = inflater.inflate(R.layout.button, root, false);
}
When we run the code, we won't see the button in the layout. This is because our button layout is not added into the main activity layout since attachToRoot is set to false.
LinearLayout has an addView(View view) method which can be used to add Views to LinearLayout. This will add the button layout into the main activity layout, and make the button visible when you run the code.
root.addView(view);
Let's remove the previous line, and see what happens when we set attachToRoot as true.
View view = inflater.inflate(R.layout.button, root, true);
Again we see that the button layout is visible. This is because attachToRoot directly attaches the inflated layout to the parent specified. Which in this case is root LinearLayout. Here we don't have to add the views manually like we did in the previous case with addView(View view) method.
Why are people getting IllegalStateException when setting attachToRoot as true for a Fragment.
This is because for a fragment you have already specified where to place your fragment layout in your activity file.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.root, fragment)
.commit();
The add(int parent, Fragment fragment) adds the fragment which has it's layout to the parent layout. If we set attachToRoot as true, you will get IllegalStateException: The specified child already has a parent. Since fragment layout is already added to the parent layout in the add() method.
You should always pass false for attachToRoot when you're inflating Fragments. It is the FragmentManager’s job to add, remove and replace Fragments.
Back to my example. What if we do both.
View view = inflater.inflate(R.layout.button, root, true);
root.addView(view);
In the first line, LayoutInflater attaches the button layout to the root layout and returns a View object which holds the same button layout. In the second line, we add the same View object to the parent root layout. This results in the same IllegalStateException we saw with Fragments (The specified child already has a parent).
Keep in mind that there is another overloaded inflate() method, which sets attachToRoot as true by default.
View inflate (int resource, ViewGroup root)

I myself was also confused about what was the real purpose of attachToRoot in inflate method. After a bit of UI study, I finally got the answer:
parent:
in this case is the widget/layout that is surrounding the view objects that you want to inflate using findViewById().
attachToRoot:
attaches the views to their parent (includes them in the parent hierarchy), so any touch event that the views recieve will also be transfered to parent view. Now it's upto the parent whether it wants to entertain those events or ignore them. if set to false, they are not added as direct children of the parent and the parent doesn't recieve any touch events from the views.
Hope this clears the confusion

There is a lot of confusion on this topic due to the documentation for the inflate() method.
In general, if attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter at that moment in time. When attachToRoot is false, the layout file from the first parameter is inflated and returned as a View and any View attachment happens at some other time.
This probably doesn't mean much unless you see a lot of examples. When calling LayoutInflater.inflate() inside of the onCreateView method of a Fragment, you will want to pass in false for attachToRoot because the Activity associated with that Fragment is actually responsible for adding that Fragment's view. If you are manually inflating and adding a View to another View at some later point in time, such as with the addView() method, you will want to pass in false for attachToRoot because the attachment comes at a later point in time.
You can read about several other unique examples concerning Dialogs and custom Views on a blog post I wrote about this very topic.
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

attachToRoot set to true means the inflatedView will be added to the parent view's hierarchy. Thus can possibly be "seen" and sense touch events (or any other UI operations) by users. Otherwise, it is just been created, not been added to any view hierarchy and thus cannot be seen or handle touch events.
For iOS developers new to Android, attachToRoot set to true means you call this method:
[parent addSubview:inflatedView];
If going further you might ask: Why should I pass parent view if I set attachToRoot to false? It is because the root element in your XML tree needs the parent view to calculate some LayoutParams (like match parent).

When you define the parent the attachToRoot determines whether you want the inflater to actually attach it to the parent or not. In some cases this causes problems, like in a ListAdapter it will cause an exception because the list tries to add the view to the list but it says it's already attached. In other cased where you're just inflating the view yourself to add to an Activity it could be handy and save you a line of code.

For example we have an ImageView , a LinearLayout and a RelativeLayout. LinearLayout is the child of RelativeLayout.
the View Hierarchy will be.
RelativeLayout
------->LinearLayout
and we have a separate layout file for ImageView
image_view_layout.xml
Attach to root:
//here container is the LinearLayout
View v = Inflater.Inflate(R.layout.image_view_layout,container,true);
Here v contains the reference of the container layout i.e the
LinearLayout.and if you want to set the parameters like setImageResource(R.drawable.np); of ImageView you will have to find it by the reference of parent i.e view.findById()
Parent of v will be the FrameLayout.
LayoutParams will be of FrameLayout.
Not attach to root:
//here container is the LinearLayout
View v = Inflater.Inflate(R.layout.image_view_layout,container,false);
Here v contains the no reference container layout but direct
reference to the ImageView that is inflated so you can set its
parameters like view.setImageResource(R.drawable.np); without
refereing like findViewById. But container is specified so that
ImageView gets the LayoutParams of the container so you can say
that the reference of container is just for LayoutParams nothing
else.
so in particular case Parent will be null.
LayoutParams will be of LinearLayout.

attachToRoot Set to true:
If attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter.
Imagine we specified a button in an XML layout file with its layout width and layout height set to match_parent.
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/custom_button">
</Button>
We now want to programmatically add this Button to a LinearLayout inside of a Fragment or Activity. If our LinearLayout is already a member variable, mLinearLayout, we can simply add the button with the following:
inflater.inflate(R.layout.custom_button, mLinearLayout, true);
We specified that we want to inflate the Button from its layout resource file; we then tell the LayoutInflater that we want to attach it to mLinearLayout. Our layout parameters are honored because we know the Button gets added to a LinearLayout. The Button’s layout params type should be LinearLayout.LayoutParams.
attachToRoot Set to false (not required to use false)
If attachToRoot is set to false, then the layout file specified in the first parameter is inflated and not attached to the ViewGroup specified in the second parameter but that inflated view acquires parent's LayoutParams which enables that view to fit correctly in the parent.
Let’s take a look at when you would want to set attachToRoot to false. In this scenario, the View specified in the first parameter of inflate() is not attached to the ViewGroup in the second parameter at this point in time.
Recall our Button example from earlier, where we want to attach a custom Button from a layout file to mLinearLayout. We can still attach our Button to mLinearLayout by passing in false for attachToRoot—we just manually add it ourselves afterward.
Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(button);
These two lines of code are equivalent to what we wrote earlier in one line of code when we passed in true for attachToRoot. By passing in false, we say that we do not want to attach our View to the root ViewGroup just yet. We are saying that it will happen at some other point in time. In this example, the other point in time is simply the addView() method used immediately below inflation.
The false attachToRoot example requires a bit more work when we manually add the View to a ViewGroup.
attachToRoot Set to false(false is Required)
When inflating and returning a Fragment’s View in onCreateView(), be sure to pass in false for attachToRoot. If you pass in true, you will get an IllegalStateException because the specified child already has a parent. You should have specified where your Fragment’s view will be placed back in your Activity. It is the FragmentManager’s job to add, remove and replace Fragments.
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.root_viewGroup);
if (fragment == null) {
fragment = new MainFragment();
fragmentManager.beginTransaction()
.add(R.id.root_viewGroup, fragment)
.commit();
}
The root_viewGroup container that will hold your Fragment in your Activity is the ViewGroup parameter given to you in onCreateView() in your Fragment. It’s also the ViewGroup you pass into LayoutInflater.inflate(). The FragmentManager will handle attaching your Fragment’s View to this ViewGroup, however. You do not want to attach it twice. Set attachToRoot to false.
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, parentViewGroup, false);
…
return view;
}
Why are we given our Fragment’s parent ViewGroup in the first place if we don’t want to attach it in onCreateView()? Why does the inflate() method request a root ViewGroup?
It turns out that even when we are not immediately adding our newly inflated View to its parent ViewGroup, we should still use the parent’s LayoutParams in order for the new View to determine its size and position whenever it is eventually attached.
Link: https://youtu.be/1Y0LlmTCOkM?t=409

Just sharing some points that i encountered while working on this topic,
In addition to the accepted answer i want to some points which could be of some help.
So, when i used attachToRoot as true, the view which was returned was of type ViewGroup i.e. parent's root ViewGroup which was passed as parameter for the inflate(layoutResource,ViewGroup,attachToRoot) method, not of type the layout which was passed but on attachToRoot as false we get the function return type of that layoutResource's root ViewGroup.
Let me explain with an example:
If we have a LinearLayout as the root layout and then we want to add TextView in it through inflate function.
then on using attachToRoot as true inflate function returns a View of type LinearLayout
while on using attachToRoot as false inflate function returns a View of type TextView
Hope this finding would be of some help...

Related

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

Android - When to pass the parent ViewGroup to LayoutInflater.inflate?

I have a simple ListView in my app. The ListView is binded to my ArrayAdapter class with a getView method implemented as follows.
class ScheduleListAdapter extends ArrayAdapter<ScheduleItem>
{
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = _activity.getLayoutInflater().inflate(R.layout.schedule_item2, null);
}
// not shown - code initialize elements of view
return view;
}
In the above code, notice that the parent ViewGroup parameter is ignored and not passed to the inflate call. I modeled this code after several books and online examples.
But now I've seen other examples on the web suggest that parent needs to be passed to inflate as follows:
View view = inflater.inflate(R.layout.schedule_item2, parent, false);
I've tried it both ways and it seems to work fine either way. But looking at the source for inflate, it seems that when the parent is passed, it can influence the LayoutParams that are used initialize to the view. But I'm uncertain how to interpret the code beyond this.
It gets confusing when you compare the above to other online examples of using LayoutInflater with Fragments and RecyclerView. Those examples always seem to explicitly pass the parent parameter to inflate. I'm assuming there are situations where it makes sense to do this.
Can someone explain when to pass ViewGroup parent to inflate and when not to?
As a result, without any known parent, all LayoutParams you declared on the root element of your XML tree will just get thrown away.
Without LayoutParams, the ViewGroup that eventually hosts the inflated layout is left to generate a default set for you. If you are lucky (and in many cases you are) these default parameters are the same as what you had in XML
Base on this documentation
ViewGroup: 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.)
It means what you experienced.
When to pass: to specify which one is the parent and this view must attach to the parent. If not attached, the only LayoutParamss from parent will be used.

The difference between the two different signature of the methods of inflate

Im having a customized ArrayAdapter for a spinner in my app.
Here's the code for its getDropDownView() method:
#Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
View vista = convertView;
if (vista==null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vista = inflater.inflate(R.layout.row_spinner,null);
}
TextView tv = (TextView) vista.findViewById( R.id.textview_entry );
if( !Utils.isSDKAbove( Utils.HONEY_COMB ) )
{
tv.setTextColor( getContext().getResources().getColor( android.R.color.primary_text_light ) );
}
tv.setText( getItem( position ) );
return vista;
}
and when tv.setText(), it throws the NullPointerException for TextView.
However , when I changed the
vista = inflater.inflate(R.layout.row_spinner, null);
to
vista = inflater.inflate(R.layout.row_spinner, parent, false);
it works.
can someone explain a bit more about the difference between the two different signature of the methods?
By declaring a parent root view, you are supplying a parent xml layout for that view. The third boolean parameter then determines whether or not this child view is attached to the parent view. Thereby determining whether child inherits the parent view's touch methods or not.
Either way the view needs to be put into perspective in terms of xml layout, so that the customisations and xml structure you've made will be implemented throughout your view hierarchy.
Using inflate (layout, parent, false)
You are using the parent layout to inflate the view (in this case spinner)
without attaching it to the parent view.
Using null you are not giving the view any layout parameters so the layout parameters for the xml for the textview doesn't exist.
From the docs:
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.)
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.
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.
Using null is not good way to detach a view from the parent view, unless it is a stand alone feature, like an alert dialog.
The view needs a root view, passing null works some of the time, but only because the program attempts to create default xml parameters for the view.
This article goes into more detail.
So why do you suppose we are given this ViewGroup if we are not supposed to attach to it? It turns out the parent view is a very important part of the inflation process because it is necessary in order to evaluate the LayoutParams declared in the root element of the XML being inflated. Passing nothing here is akin to telling the framework “I don’t know what parent this view will be attached to, sorry.”
The problem with this is android:layout_xxx attributes are always be evaluated in the context of the parent view. As a result, without any known parent, all LayoutParams you declared on the root element of your XML tree will just get thrown away, and then you’ll be left asking “why is the framework ignoring the layout customizations I defined? I’d better check SO and then file a bug.”

Get a reference to something I just inflated

I have an outer viewgroup (a ViewFlipper), and I want to programmatically put an inner view inside of it (a LinearLayout). I then want a reference to that inner view so I can do things with it later. So I'll have a line like this:
inflater.inflate(R.layout.my_linear_layout, myViewFlipper, true);
How can I get access to the inner view that I just inflated? The android docs for LayoutInflater claim that .inflate returns a reference to "the root View of the inflated hierarchy", but adds that "If root was supplied and attachToRoot is true, this is root", which I interpret to mean that in my case .inflate will return a reference to myViewFlipper.
try this
LinearLayout layout = (LinearLayout ) inflater.inflate(R.layout.my_linear_layout, null, false);
myViewFlipper.addView(layout);
You can also just search for that specific view?
LinearLayout layout = findViewById(R.id.the_id_of_the_linear_layout);
Or you can retrieve the first child of the ViewFlipper after inflating?
Anyway, inflate returns a View that you can use to search, find or do whatever you want with.

RelativeLayout check runtime if is removed or not

In an activity I am changing one of the ViewGroup content runtime: buttons action, other events.
At a specific case I need to check if a child is in this layout or not ( in this case the child is another RelativeLayout, which hold other views)
How can I check runtime, programmatically if child_1_RelativeLayout is there or is already removed from view tree, his parent is parentRelativeLayout
The getParent() is usefully? - not much explanation how to use it, thanks.
In case you have stored your views you can use getParent() to check if view is a direct child for other view. After removing view its parent field will be cleared. For example:
ViewGroup parent = ...;
View child = ...;
assert(child.getParent() == parent); // <-- true
parent.removeView(child);
assert(child.getParent() == parent); // <-- false
Not really sure if I understand your question correctly, but:
when you add the relative layout, be sure to first give it an id (either in your layout.xml file, or from code)
to check existence of the relative layout within the ViewGroup, use ViewGroup's findViewById() method (inherited from View) and pass it the id you've given to the relative layout
if it returns null, the relative layout is not there, otherwise findViewById() will find it
So in short, findViewById() is not only defined for an Activity, but you can call this on any view you would like to use as a starting point for your search.

Categories

Resources