Search code examples
androidandroid-arrayadapterlayout-inflater

how do you use the second parameter in the inflate method of the LayoutInflater class, Android


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.


Solution

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