Akshay Abhyankar Akshay Abhyankar - 4 months ago 52
Android Question

What is LayoutInflater in Android?

I am unable to understand the exact use of LayoutInflater in Android.

What exactly the role of LayoutInflater is ? I need someone to explain this to me.


What is Layoutinflater ?

LayoutInflater is a class (wrapper of some implementation or service), you can get one:

LayoutInflater li = LayoutInflater.from(context);

How to use Layoutinflater ?

You feed it an XML layout file. You need not give full file address, just its resource id, generated for you automatically in R class. For example, a layout file which look like:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"



saved as /res/layout/my_layout.xml.

You give it to LayoutInflater like:

  View v = li.inflate(R.layout.my_layout,null,false);

What did Layout Inflater do ?

That v is now a LinearLayout object (LinearLayout extends View) , and contains a TextView object, arranged in exact order and with all properties set, as we described in the XML above.

TL;DR: A LayoutInflater reads an XML in which we describe how we want a UI layout to be. It then creates actual Viewobjects for UI from that XML.