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

我们两清 提交于 2019-12-03 02:42:10

问题


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!


回答1:


There is not much of a difference between them.

As doc says public abstract Object getSystemService (String name)

A LayoutInflater for inflating layout resources in this context.

And for the public static LayoutInflater from (Context context)

Obtains the LayoutInflater from the given context.

You can check this thread Is there any difference between getLayoutInflater() and .getSystemService(Context.LAYOUT_INFLATER_SERVICE)




回答2:


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.




回答3:


The only difference is the context that you use. If the context that you use with LayoutInflater.fromContext() or context.getSystemService(...) is actually an Activity, it should be equivalent to Activity.getLayoutInflater(). If it's the application object, you might have problems inflating views that contain fragments, IIRC.




回答4:


Actually I think that the getLayoutInflater() - Method of Activity is a convenience - method.

Remember that Activity subclasses Context, so all of the Methods available within Context are also available in the Activity Class.

Internally there will be a call to LayoutInflater.fromContext() or context.getSystemService(), so I would stick to context.getSystemService both to avoid the unnecessary method call as well to clarify that I am making a call to a system service.



来源:https://stackoverflow.com/questions/20994728/what-is-the-correct-way-to-get-layout-inflater-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!