Search code examples
androidandroid-widgetlayout-inflaterfindviewbyid

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?


Solution

  • 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.