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?
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.
"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.
LayoutInflater is a class used to instantiate layout XML file into its corresponding view objects which can be used in Java programs. In simple terms, there are two ways to create UI in android. One is a static way and another is dynamic or programmatically.
Put simply, an inflater allows you to create a View from a resource layout file so that you do not need to create everything programmatically. In your example, you inflate the layout R. layout. list_mobile .
If looking at the source of View.inflate()
we see this:
public static 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.
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.
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