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!
use outside of your activity
Within your activity
Check this
If you open up the Android source you can see that the LayoutInflator.from method looks like so:
and there is no difference
As long as the Activity or Window that calls
getLayoutInflater()
has the same Context that would callgetSystemService()
, there is no difference.Actually I think that the
getLayoutInflater()
- Method of Activity is a convenience - method.Remember that
Activity
subclassesContext
, so all of the Methods available withinContext
are also available in theActivity
Class.Internally there will be a call to
LayoutInflater.fromContext()
orcontext.getSystemService()
, so I would stick tocontext.getSystemService
both to avoid the unnecessary method call as well to clarify that I am making a call to a system service.The only difference is the context that you use. If the context that you use with
LayoutInflater.fromContext()
orcontext.getSystemService(...)
is actually an Activity, it should be equivalent toActivity.getLayoutInflater()
. If it's the application object, you might have problems inflating views that contain fragments, IIRC.There is not much of a difference between them.
As doc says public abstract Object getSystemService (String name)
And for the public static LayoutInflater from (Context context)
You can check this thread Is there any difference between getLayoutInflater() and .getSystemService(Context.LAYOUT_INFLATER_SERVICE)