The inflate method of the LayoutInflater
abstract class has as the second parameter of the inflate method that takes ViewGroup
root. From the documentation, it is mentioned as an "Optional view to be the parent of the generated hierarchy."
Can someone give an example on how to use this parameter? And what would you put in there? A ViewGroup
can be any type of layout like LinearLayout
.
I have not quite understood what to do with this parameter. If the view you are inflating is not part of the layout that is entered here then it would give an error. Don't understand the purpose of it.
More from the documentation:
public View inflate (XmlPullParser parser, ViewGroup root)
Added in API level 1
Inflate a new view hierarchy from the specified xml node. Throws InflateException if there is an error.
Important for performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater
with an XmlPullParser
over a plain XML file at run time.
Parameters parser XML dom node containing the description of the view hierarchy.
root Optional view to be the parent of the generated hierarchy. Returns The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
LayoutInflater creates View objects based on layouts defined in XML. There are several different ways to use LayoutInflater, including creating custom Views, inflating Fragment views into Activity views, creating Dialogs, or simply inflating a layout file View into an Activity.
In this context, Inflate means reading a layout XML (often given as parameter) to translate them in Java code. This process happens: in an activity (the main process) or a fragment.
LayoutInflater - this is a class, which can create a View element from the layout files' content. The inflate method is that one which does it. There are several implementations of this method with different parameters.
inflate method returns the parent View of inflated xml
In case you don't pass root ViewGroup, inflated xml root View will be returned
In case you pass root ViewGroup, root View of root ViewGroup will be returned
I'm not really sure what part of that confuses you, to be honest. You can pass in any ViewGroup, to be the parent of the views that you're creating dynamically.
For example:
private static View mView = inflater.inflate(R.layout.fragment_featured, container, false);
This will inflate the layout contained in the fragment_featured xml file within the container (as a parent). The type of the container ViewGroup is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With