As you might already know by now that every visible component in Android is a View
. That includes Button
, Spinner
, TextView
, EditText
and the likes. You are also right about the way we access the Views that are defined in a xml file in our program, by inflating it and then finding the view by using it's id. The usual way to do this is by using setContentView()
method.
But there is this pretty useful class called LayoutInflater
that can be used to "inflate" a layout. Now consider the scenario where you have a ListView
in your xml file that you inflated using setContentView()
method. In this ListView you want the items to contain an ImageView
and a TextView
. The default list-item just have a TextView
. So you decided to write up a custom adapter in which you'll be using a new listitems.xml in which you have a TextView
and ImageView
defined. Now you can't use setContentView()
in this case as it will inflate this layout on the whole activity which obviously you don't want. So you use LayoutInflater
in this case to help you out. You temporarily inflate a layout using inflate()
method. The first argument takes the layout file which is needed to be inflated. The second argument is the root of this newly inflated layout. In our case it can be set to the ListView
in which the layout is going to be actually inflated.
So when you use this inflate()
method, a View
is returned containing the views that are inside the inflated xml. Now with this returned view instance you can call findViewById()
to get the contained views to set text to the TextView
and image source to the ImageView
.
More often than not, you'll end up using LayoutInflater
as it's use cases are wider than the scope of this discussion.