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?
The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.
inflater.inflate will -Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. In simple terms inflater. inflate is required to create view from XML .
android.view.LayoutInflater. Instantiates a layout XML file into its corresponding android. view. View objects. It is never used directly.
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" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout> 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.
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