在 Android api 级别 27 中将 getContext() 覆盖为非空是个坏主意?

Bad idea to override getContext() to non-null in Android api level 27?

我正在使用 kotlin,最近使用 compileSdkVersion/targetSdkVersion 27 更新了我的应用程序。我遇到了一些编译错误,例如,上下文现在可以为空(上下文?)而不是非空。 我有一个基本片段 class,其他片段继承自该片段。拥有这个功能是不是一个坏主意?

override fun getContext(): Context {
    return super.getContext()!!
}

在父函数中,我看到你有这样的代码:

/**
 * Return the {@link Context} this fragment is currently associated with.
 */
@Nullable
public Context getContext() {
    return mHost == null ? null : mHost.getContext();
}

其中 mHost 是:

// Host this fragment is attached to.
FragmentHostCallback mHost;

但据我所知,该片段将始终附加到主机。 有没有mHost为null的场景?

编辑:在支持库 v27.1.0 中,片段现在具有 requireContext()、requireActivity()、requireHost() 和 requireFragmentManager() 方法,return 等效 get 方法的 NonNull 对象或 throw IllegalStateException。

https://developer.android.com/reference/android/support/v4/app/Fragment.html#requireContext()

可能存在片段未附加到主机的情况。最简单的例子是当片段用它的空构造函数实例化并且没有附加到任何东西时。如果您在构造函数中调用 getContext()(或从构造函数调用的方法),它将产生 null 值。

这意味着将 getContext() 覆盖到 return super.getContext() 是没有意义的。您也许可以摆脱一些 空检查 ,但如果它是 null,您的应用程序将崩溃。

原因是在某些情况下片段尚未附加到父级但您尝试访问它,在这种情况下上下文将是null.Best示例是当您有包含多个片段的选项卡并且您继续在选项卡之间切换,最可能的情况是片段将被分离并需要时间将其附加回去,但您已经切换到其他选项卡导致您的应用程序崩溃。因此,保持上下文可为空是最佳实践之一。