Java 在安卓系统中使用布局充气器的正确方法是什么?
有一种方法可以使布局更平坦:Java 在安卓系统中使用布局充气器的正确方法是什么?,java,android,layout-inflater,Java,Android,Layout Inflater,有一种方法可以使布局更平坦: LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 另一种方式是: LayoutInflater inflater = LayoutInflater.from(context); 第三个(当我参加活动时)是: 那么它们之间的区别是什么呢 请注意,当我将第三个充气器发送到适配器时,我的应用程序工作正常。但是当我发送
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
另一种方式是:
LayoutInflater inflater = LayoutInflater.from(context);
第三个(当我参加活动时)是:
那么它们之间的区别是什么呢
请注意,当我将第三个充气器发送到适配器时,我的应用程序工作正常。但是当我发送上下文并通过第二种方式创建充气机时,它没有 它们之间没有太大区别 正如医生所说 用于在此上下文中增加布局资源的LayoutFlater 而对于 从给定上下文获取LayoutInflater
您可以检查此线程唯一的区别是您使用的上下文。如果与
LayoutInflater.fromContext()
或context.getSystemService(…)
一起使用的上下文实际上是一个活动,则它应等同于Activity.getLayoutInflater()
。如果它是应用程序对象,则可能会在膨胀包含片段的视图时遇到问题,IIRC。在活动之外使用
LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE );
LayoutInflater inflater = getLayoutInflater();
在你的活动中
LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE );
LayoutInflater inflater = getLayoutInflater();
如果打开Android源代码,可以看到LayoutInflator.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;
}
没有区别
只要调用
getLayoutFlater()
的活动或窗口的上下文与调用getSystemService()
的上下文相同,就没有区别。实际上,我认为getLayoutFlater()
-活动方法是一种方便的方法
请记住Activity
子类Context
,因此Context
中可用的所有方法也可在Activity
类中使用
内部将调用
LayoutInflater.fromContext()
或context.getSystemService()
,因此,我会坚持使用context.getSystemService
这两种方法,以避免不必要的方法调用,并澄清我正在调用系统服务。没有太大区别请在grepcode上查看这些方法,以便您可以从美学角度理解它们之间的差异,第一个:)否则,都一样。看看这个可能的重复:你做了y天,我从过去五天一直在搜索,但没有发现这个错误,现在你的解决方案运行良好@Shyam Deore