Alexander
Alexander

Reputation: 48252

getLayoutInflater vs LayoutInflater.from

Studying some (known to be good) code I can see the logic as follows:

if (getContext() instanceof Activity) {
      inflater=((Activity)getContext()).getLayoutInflater();
}
    else {
      inflater=LayoutInflater.from(getContext());
}

I wonder, why this if/else, how it is better to, just, using LayoutInflater.from in all cases?

Upvotes: 14

Views: 3729

Answers (3)

Araz
Araz

Reputation: 190

from the android documentation it is suggested to use getLayoutInflater( ) instead.The documentation says the following about the LayoutInflator.from.. :

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead,

it suggests to use :

use Activity.getLayoutInflater() or Context#getSystemService to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.

in other words for the sake of simpler code and performance you better use getLayoutInflater from the context that has already been initilized.

Upvotes: 0

laalto
laalto

Reputation: 152817

It doesn't really matter much.

Activity delegates getLayouInflater() to Window. The usual policy implementation of Window PhoneWindow in turn initializes its inflater with LayoutInflater.from(context) where context is the activity.

So the inflater object is really the same, using the same Context in case of an activity.

LayoutInflater.from() is really a wrapper for Context.getSystemService(). Now, system services are looked up by name from a map and then retrieved from a cache. This lookup has some overhead when compared to accessing an already initialized member variable in Activity.

So it smells like a micro optimization that does not likely affect much runtime performance when compared to actual view hierarchy inflation.

This optimization can actually have negative impact on developer productivity as people need to stop and spend some thinking why the code is there.

Upvotes: 17

MiltoxBeyond
MiltoxBeyond

Reputation: 2731

By the same code it seams that LayoutInflater.from is used in the contexts that are not an activity. I would assume that using the Activity's inflater reuses an already created inflater versus the other choice which would create a layoutinflater from a context.

The only change I would make is saving the context in a variable to prevent calling the same function and retrieving the same value from the object repeatedly:

Context ctx = getContext();
if(ctx instanceof Activity) {
  inflater = ((Activity)ctx).getLayoutInflater();
}
else {
  inflater = LayoutInflater.from(ctx);
}

Android has a lot of optimizations in place to reuse items when available, like the views for ListViews which can be reused.

Upvotes: 4

Related Questions