I am aware of a post that was made before this pertaining to the same topic, however it was in java.
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
// create a new view
val adapterLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
return ItemViewHolder(adapterLayout)
}
This was the definition the docs gave me, "Instantiates a layout XML file into its corresponding android.view.View objects." What does this mean?
Then there is the inflate method which the docs state "Inflate a new view hierarchy from the specified XML node."
Could someone explain to me in simpler terms what Layoutinflater and it's method inflater do?
TL;DR The "inflater" reads the XML layout file, which defined what View objects to create and where to put them, and actually does the View creation.
Some helpful terms:
View - Anything that inherits from the View class, e.g. TextView or Button
Layout - an arrangement of different View objects on the screen (this is what you see looking at the app)
XML Layout File - An XML text file that describes a layout - specifically what Views go in that layout and how to position them (e.g. activity_main.xml). The XML file is not the layout, it is a description of how to build the layout.
Inflater - A routine/object that takes an XML layout file, reads it, and actually creates the Layout (arrangement of View objects). Calling inflate on the inflater returns a View object that contains everything you defined in the XML file.
More Details
A screen you see in an Android app is a collection of "Views". These may be things like TextView, ConstraintLayout, EditText, Button, etc... - all different types of views (they all inherit from the View class).
When you build up a layout of those views you typically use an XML file to define what views to create and where to position those views. The XML file is not the view itself, it is just a description of how the views should be constructed and positioned.
The layout inflater takes that XML file and actually goes about building the views as you see them on the screen in the app. When you call inflate it reads all the data about the views from the XML file, creates instances of those views, and positions them in the parent view container based on what you told it to do in the XML file.
In the example code you showed (from a RecyclerView adapter) the XML file it is referring to is the one that describes how to arrange the views in a given row in the RecyclerView. Once the adapter "inflates" the view for that row, then the actual view objects (e.g. TextViews) have been created and positioned within that row.
The RecyclerView adapter will call this method multiple times, to "inflate" a new unique view instance for each displayed row. The "recycler" part of the RecyclerView means that it will try not to call this more than necessary, and will re-use the views on new rows where it can as you scroll.
Additional Reading
Official docs,
What does layout inflater in Android do?
What is layout inflater and how do I use it?
From what I understand, the LayoutInflater converts XML into Views. But when I use Buttons, TextViews or other widgets in code, I simply have to use findViewById() without having to inflate these Views first. Are these views automatically inflated? If so, when are views automatically inflated and when do you have to inflate them manually?
You just have to inflate an xml layout, and then all the viewgroups and views (buttons,textview,edittext,etc.) will automatically be shown.
So in an Activity class, oncreate method has a line SetContentview(), this inflates the xml layout.
An Activity needs to include a call to setContentView(R.layout.<your_layout_here>) in its onCreate method. That inflates the XML in the specified layout into the view hierarchy for the Activity. For a Fragment, override the onCreateView method like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.<your_layout_here>, container, false);
}
Once you've inflated a layout (and all of its children Views) into the view hierarchy, you can then use findViewById(R.id.<your_view_id>) to get a reference to the actual View object that you've inflated into the hierarchy and play with it.
you inflate your views manually if you create your activity and xml manually.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
}
Few things are here:
1. View for your activity(UI screen), that is set by setContentView() method.
2. View for a specific UI component e.g. Button, that is either created in xml of your activity_layout or you can inflate a separate xml layout file for your specific UI component. The best example and use is like inflating an xml layout file for your customised Toast.
So, here is the thing that relates setContentView() and inflating an xml layout file for a separate view:
Both of these provides a layout for view and view components, both of them creates a binary output for layout and use them as described above.
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.
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.
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...