Search code examples
androidlayout-inflater

What is the difference between the inflaters


What is the difference between doing

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

and inflater = LayoutInflater.from(activity);


Solution

  • What is the difference between the inflaters

    Difference is that in second example (via static method), you don't need to cast Object to LayoutInflater because it returns directly LayoutInflater instance.

    First case returns generally Object that you have to explicitly cast to LayoutInflater. But result of both methods is new instance of LayoutInflater

    Is up to you which method you'll pick up. I usually use LayoutInflater.from(); method and never have problems. I don't need to cast from Object and it'll make a trick.

    As @CommonsWare mentioned, you can also call

    getLayoutInflater()
    

    If you are in Activity class (it's method of Activity). But when you are not in Activity you need to have Context variable and then you can call (for example from ListAdapter):

    ((Activity) context).getLayoutInflater();
    

    But i think when you are not in Activity it's much easier and efficient to call LayoutInflater.from(); instead of approaches above.