getLayoutInflater()和.getSystemService(Context.LAYOUT_INFLATER_SERVICE)之间有什么区别吗?

32
简单的“不”回答可以让我冷静下来。如果有任何区别,那是什么?
4个回答

43

只要调用getLayoutInflater()的Activity或Window具有与调用getSystemService()相同的Context,它们之间没有任何区别。


证明 你可以追踪由getLayoutInflater()返回的LayoutInflater到LayoutInflater.from(),并且从源代码中可以看到这只是getSystemService()的一个快捷方式:

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

24
其他证明:getLayoutInflater() == getSystemService(Context.LAYOUT_INFLATER_SERVICE) 返回值为 true - Brais Gabin
不,"==" 返回 "true" 是因为这两个实例是相同的。如果 "==" 返回 "true",那么 "equals()" 如果被(很好地)实现,总是会返回 "true"。 - Brais Gabin

4

有至少一种情况下,只能使用

getSystemService(Context.LAYOUT_INFLATER_SERVICE);

而不能使用相应的方法

getLayoutInflater

这种情况出现在任何对象类中。例如,我有一个叫做objectA的实例。在objectA中,我想要将一个视图填充到父视图上(在ArrayAdapter中为其列表视图填充自定义行)。在这种情况下,context.getLayoutInflater无法工作,因为没有与上下文相关联的活动或窗口。此时只能使用getSystemService(Context.LAYOUT_INFLATER_SERVICE)


3

这是定义LayoutInflater的方式。

LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
getLayoutInflater()只是通过返回LayoutInflater来提供对窗口从其上下文检索的LayoutInflater实例的“快速访问”(来自文档)。
同样,getSystemService(Context.LAYOUT_INFLATER_SERVICE)用于检索此上下文中用于填充布局资源的LayoutInflater。
因此,实际上两者之间没有区别。
来源:文档

快速访问此窗口从其上下文检索到的LayoutInflater实例。
引用来源:http://developer.android.com/reference/android/view/Window.html#getLayoutInflater%28%29
- Sam

2

没有区别。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接