I am unable to understand the use of LayoutInflater in Android.
What exactly is the role of LayoutInflater, and how to use it for a simple Android app?
I am unable to understand the use of LayoutInflater in Android.
What exactly is the role of LayoutInflater, and how to use it for a simple Android app?
From the Android docs:
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:
Useful in creating Custom Views
See
Some basics for LayoutInflater-
This class is used to instantiate layout XML file into its corresponding View objects.
It is never used directly. Instead,
getLayoutInflater()
orgetSystemService(String)
to retrieve a standard LayoutInflater instance that is already hooked up to the current context.It is most likely to get closed but the role of layout inflater is to create a
view
from the supplied layout fileit is creating the view from the
R.layout.list_item
file and proving thatview
.when you run
setContentView(layout file name)
, you can runfindViewById(id of the widget)
. You dont need to do something likexyz.findViewById
. The context of your app is set to that layout file and allfindBiewById
call will refer to that layout file.There are cases when you need to pick up one more layout file, like a CustomDialog, ListElement or a Custom Toast. At this time you wont want to create a Activity just for these small UI components, that that time you programmatically need to get a programmatic reference to your layout file, so that you can run findViewById on it.
Inflate, blows the layout like a balloon and give you the balloon for you to watch around it all the colors and objects drawn on it :). Inflate gives you the object reference to that layout to call findViewById on.
Hope this clears.
What is Layoutinflater ?
LayoutInflater
is a class (wrapper of some implementation or service), you can get one: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:saved as
/res/layout/my_layout.xml
.You give it to
LayoutInflater
like:What did Layout Inflater do ?
That
v
is now aLinearLayout
object (LinearLayout
extendsView
) , and contains aTextView
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 actualView
objects for UI from that XML.