Skip to content Skip to sidebar Skip to footer

View.inflate Vs Layoutinflater

What is the main difference in using LayoutInflater and static method View.inflate()? Are there any drawbacks in using any of them or maybe they serve different purposes?

Solution 1:

If looking at the source of View.inflate() we see this:

publicstatic View inflate(Context context, int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
}

So, internally, the inflate() method of View class uses the LayoutInflater, which makes me assume there's no difference.

Solution 2:

View.inflate() does internally call LayoutInflator.inflate(resource, root) which in turn calls LayoutInflator.inflate(resource, root, root != null). The third parameter is booleanAttachToRoot which the docs describe as:

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.

In other words, with View.inflate(), you can't tell the inflator not to attach your new view to the reference root ViewGroup.

Solution 3:

I just get a problem from that. And here is what I find.

View.inflate use LayoutInflator.inflate(id, Viewparent). It will ignore parent's layoutparam if Viewparent paramater is null.

But. Inflator.inflate has another api inflate(id, View parent, boolean attach). This method is useful when you need init this view with parent layoutparamter

Post a Comment for "View.inflate Vs Layoutinflater"