Search code examples
androidviewlayoutparams

what does 3rd parameter of public View inflate (int resource, ViewGroup root, boolean attachToRoot) do?


According to android.developer.com

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.

What is this subclass of LayoutParams? What happens to the layout parameters of the resource mentioned in the function parameter?

I tried both combination of true and false as 3rd parameter, only difference seems to be whether the the resource is attached as child. The layout parameters for resource mentioned in its xml file, stay in effect in both cases.


Solution

  • What does public View inflate (int resource, ViewGroup root, boolean attachToRoot) really means ?

    It points to the layout resource you want to inflate. The second parameter is the root view of the hierarchy you are inflating the resource to attach to. When the third parameter is present, it governs whether or not the inflated view is attached to the supplied root after inflation.

    The last two parameters that can cause a bit of confusion. With the two parameter version of this method, LayoutInflater will automatically attempt to attach the inflated view to the supplied root. However, the framework has a check in place that if you pass null for the root it bypasses this attempt to avoid an application crash.

    In most cases it will throw an Exception later on if LayoutInflater is allowed to automatically attach the inflated view to the root.

    So why this ViewGroup is given if we are not supposed to attach to it?

    It turns out the parent view as 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 “Sorry because I don’t know what parent this view will be attached to actually”.

    reference