What is LayoutInflater? Why we need to inflate and when?


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 static way and another is dynamic or programmatically.
Suppose we have a simple layout main.xml having one textview and one edittext as follow.

We can display this layout in static way by

Dynamic way of creating a view means the view is not mentioned in our main.xml but we want to show with this in run time. For example We have another xml in layout folder as footer.xml

We want to show this textbox in run time within our main UI. So here we will inflate text.xml . See how

Here I have used getSystemService (String) to retrieve a  LayoutInflater instance. I can use getLayoutInflator() too to inflate instead of using getSystemService (String)  like below

We have inflated the view footer using inflater and converted it Textview object. In this example we have inflated a simple textview. If you want to know how to inflate a listview , check this Inflating Listview post.

aaa bbb

You may also like...

Leave a Reply