Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between LayoutInflater.inflate and findViewById

What is the difference between getting a reference to a widget like this:

TableRow row = findViewById(R.id.table_row);

and:

TableRow row = (TableRow)LayoutInflater.from(this).inflate(R.layout.table_row, null);

Is there also a difference when the TableRow is a root of its layout or if its just a small part of a layout?

like image 598
Yonatan Nir Avatar asked Jan 18 '15 21:01

Yonatan Nir


People also ask

What is LayoutInflater used for?

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.

What is view inflate?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

Why do we use the layout Inflater in listview?

Put simply, an inflater allows you to create a View from a resource layout file so that you do not need to create everything programmatically.


1 Answers

What is the difference...

The first one is retrieving an existing widget within your activity.

The second one is reading in an XML file and is creating new widgets. The second one is also somewhat buggy, in that you infrequently want to use LayoutInflater.from() (you typically use getLayoutInflater() on your Activity), and you infrequently want to use that inflate() variant (if you do not provide a parent container, layout resources with a root RelativeLayout element will misbehave).

Is there also a difference when the TableRow is a root of its layout or if its just a small part of a layout?

Yes. The difference is the same as before: retrieving an existing widget or creating a new one.

like image 53
CommonsWare Avatar answered Sep 27 '22 01:09

CommonsWare