【问题标题】:What is the guaranteed way to get not null Context in Fragment?在片段中获得非空上下文的保证方法是什么?
【发布时间】:2019-01-27 12:15:39
【问题描述】:

我看到了很多关于如何在 BaseFragment 中获取上下文的示例:

protected lateinit var ctx: Context

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

然后我们可以在扩展 BaseFragment 的其他片段中使用上下文实例。 Onetwothree (it's offered to get Context from onViewCreated()) 等等。 看起来像是解决方法。

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

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

【问题讨论】:

    标签: android android-fragments android-context


    【解决方案1】:

    你不能保证上下文是 100% 非空的,这就是为什么它被标记为可空 (?),所以你提到的“解决方法”实际上会在活动分离的情况下导致异常。 为避免它,请不要标记 ctx:Context as lateinit var 使其可以为空 protected var ctx:Context? = null 并在每次要使用它时检查它的状态。

    【讨论】:

    • 即使我不会在onDetach()中分配空值,它也会为空?我的意思是它引用了活动上下文并且不会存储在我的 BaseFragment 中?如果活动分离,我的 lateinit var 会将值覆盖为 null?
    • 是的,在这种情况下 context 只是对 Activity 的引用,如果 Activity 死了,无论它存储在哪里,上下文都会死。
    • 感谢您的全面解答!
    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多