Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View.inflate vs LayoutInflater

Tags:

android

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?

like image 739
Heisenberg Avatar asked May 28 '14 10:05

Heisenberg


People also ask

What is LayoutInflater inflate?

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.

What does inflated view mean?

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

What is LayoutInflater from in Android?

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.

What is Inflater for?

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 .


2 Answers

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.

like image 86
Andy Res Avatar answered Nov 14 '22 03:11

Andy Res


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.

like image 42
vonWippersnap Avatar answered Nov 14 '22 01:11

vonWippersnap