我很长一段时间以来一直有这个疑问,当我使用 android 片段并且需要实例化 Context 时,或者我需要将 Context 作为其他函数的参数传递时,我可以选择在 getContext( )和 requireContext() 方法来实现这一点,我通常更喜欢使用 requireContext(),但只是因为当我使用 getContext() 时,IDE(Android Studio)有时会显示警告。但是使用一种或另一种方法的结果似乎是无论我选择什么,都是一样的。
我的问题是,这两种方法有什么区别吗?如果是这种情况,哪一个更好,或者每种情况我应该使用哪一个?
getContext()
返回可为空的 Context
。
requireContext()
返回非空 Context
,或者在不可用时抛出 IllegalStateException
。
如果您的代码处于生命周期阶段,您知道您的片段已附加到上下文,只需使用
requireContext()
来获取 Context
并让静态分析器对潜在的 NPE 问题感到满意。
如果您的代码超出常规片段生命周期(例如,异步回调),您可能最好使用
getContext()
,自己检查其返回值,并且仅在其非空时才继续使用它。
明确可空性在 Kotlin 中更为重要,它内置于语言的类型系统中。
虽然 Laalto 的答案是正确的,但我添加代码来证明 requireContext() 和 getContext 之间的区别。
在 Fragment.java 中,您应该看到以下代码。
@NonNull
public final Context requireContext() {
Context context = getContext();
if (context == null) {
throw new IllegalStateException("Fragment " + this + " not attached to a context.");
}
return context;
}
可以看到,当上下文为null时,requireContext()方法会抛出异常。
@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
另一方面,如果您看到 getContext() 的代码,那么在调用时您有可能会得到 null 值。