Last Updated: July 11, 2019
·
8.238K
· spectralnischay

LayoutInflater - Android

Developers normally don't see the use, or do not attach the parent at inflation properly.

The wrong way:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.your_layout, null);

The right way:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.your_layout, container, false);

When layout are declared in XML, they include layout parameters (all XML attributes that are prefixed with layout_). These maybe lost when the parent is not passed at time of inflation. Additionally, it is more efficient to prepare the View for the parent at the time of inflation. This is one of the reasons why Android provides the developer with the parent/container at the time of inflation.