我正在使用 kotlin,最近使用 compileSdkVersion/targetSdkVersion 27 更新了我的应用程序。我遇到了一些编译错误,例如,上下文现在可以为空(上下文?)而不是非空。 我有一个基本 fragment 类,其他 fragment 从中继承。拥有这个功能是不是一个坏主意?
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;
但据我所知, fragment 将始终附加到主机。 是否存在 mHost 为空的情况?
编辑:在支持库 v27.1.0 中, fragment 现在具有 requireContext()、requireActivity()、requireHost() 和 requireFragmentManager() 方法,它们返回等效 get 方法的 NonNull 对象或抛出 IllegalStateException。
参见 https://developer.android.com/reference/android/support/v4/app/Fragment.html#requireContext()
最佳答案
可能存在 fragment 未附加到主机的情况。最简单的例子是当 fragment 用它的空构造函数实例化并且没有附加到任何东西时。如果您在构造函数(或从构造函数调用的方法)中调用 getContext()
,它会产生一个 null
值。
这意味着覆盖 getContext()
以返回 super.getContext()
是没有意义的。您或许能够摆脱一些null-checks,但如果它是null
,您的应用将会崩溃。
关于android - 在 Android api 级别 27 中将 getContext() 覆盖为非空是个坏主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663177/