我浏览了一些教程,在 Android Doc 中,它说在实例化 LayoutInflater 时不要直接访问它。谷歌文档中的示例:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
我经历过的教程是这样的:
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
所以我真正不明白的是除了明显不同的代码之外还有什么区别。任何解释都非常感激。我认为 Android Doc 应该是我们遵循的文档,但我不确定它是否会有所不同。
如果打开 Android 源代码,您可以看到 LayoutInflater.from 方法如下所示:
/**
* 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;
}
这意味着您问题中的两行代码执行相同的操作。不确定您阅读的教程到底说了什么,但我没有看到功能上有任何差异。使用from
方法很好,因为它需要更少的输入,仅此而已。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)