What is the correct way to get layout inflater in Android?

Hamzeh Soboh picture Hamzeh Soboh · Jan 8, 2014 · Viewed 24.3k times · Source

There is a way to get layoutInflater:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

and another way is:

LayoutInflater inflater = LayoutInflater.from(context);

a third one (when I am in an Activity) is:

LayoutInflater inflater = getLayoutInflater();

So what is the difference between them?

Note that when I sent the third inflater to my adapter, my application worked. But when I sent the context and created the inflater via the second way, it didn't!

Answer

sachin10 picture sachin10 · Jan 8, 2014

use outside of your activity

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(
        Context.LAYOUT_INFLATER_SERVICE );

Within your activity

     LayoutInflater inflater = getLayoutInflater();

Check this

If you open up the Android source you can see that the LayoutInflator.from method looks like so:

    /**
     * Obtains the LayoutInflater from the given context.
     */
    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

and there is no difference

As long as the Activity or Window that calls getLayoutInflater() has the same Context that would call getSystemService(), there is no difference.