简单的“不”回答可以让我冷静下来。如果有任何区别,那是什么?
只要调用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;
}
有至少一种情况下,只能使用
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
而不能使用相应的方法
getLayoutInflater
这种情况出现在任何对象类中。例如,我有一个叫做objectA的实例。在objectA中,我想要将一个视图填充到父视图上(在ArrayAdapter中为其列表视图填充自定义行)。在这种情况下,context.getLayoutInflater无法工作,因为没有与上下文相关联的活动或窗口。此时只能使用getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
这是定义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
没有区别。
getLayoutInflater() == getSystemService(Context.LAYOUT_INFLATER_SERVICE)
返回值为true
。 - Brais Gabin