What is the difference between calling LayoutInflater directly and not?

荒凉一梦 提交于 2019-12-04 18:58:12

问题


I went through some tutorials, and in the Android Doc, it says not to access LayoutInflater directly when instantiating it. Example from the google Doc:

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

The tutorial I went through is this one:

LayoutInflater inflater = LayoutInflater.from(parent.getContext());

So what I don't really understand is what the difference is besides the obvious different code. Any explanation much appreciated. I assume that the Android Doc should be the one we follow, but I am not sure if it makes a difference.


回答1:


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;
}

That means the two lines of code in your question do the same thing. Not sure what the tutorial you read says exactly but I don't see any difference in functionality. Using the from method is nice since it requires a little less typing, that's it.




回答2:


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

You are getting LayoutInflater Service Provider from System Manager

LayoutInflater inflater = LayoutInflater.from(parent.getContext());

You are using static method from LayoutInflater Class

I would say that difference is only in code and how you write this also calling stack but result is same - you will get LayoutInflater.

More about this

Regards



来源:https://stackoverflow.com/questions/10776676/what-is-the-difference-between-calling-layoutinflater-directly-and-not

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