在 Fragment 中获取 not null Context 的保证方法是什么?

What is the guaranteed way to get not null Context in Fragment?

我看到很多关于如何在 BaseFragment 中获取 Context 的示例,如下所示:

protected lateinit var ctx: Context

override fun onAttach(context: Context?) {
    super.onAttach(context)
    ctx = context!!
}

然后我们可以在扩展 BaseFragment 的其他片段中使用上下文实例。 One, two, 等等。 看起来像是解决方法。

我也遇到过在 Fragment 中使用 getActivity() 或 getContext() 时出现 "fragment detached from Activity" 异常的情况。

那么,什么才是真正的方法呢?

你不能保证上下文是 100% 非空的,这就是为什么它被标记为可以为空的(?),所以你提到的 'workaround' 实际上会导致异常,以防 [=15= 】 超然。 为避免它,请不要标记 ctx:Context as lateinit var 使其可为空 protected var ctx:Context? = null 并在每次使用时检查它的状态。