gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:20:35 29 4
gpt4 key购买 nike

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

protected lateinit var ctx: Context

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

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

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

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

最佳答案

您不能保证上下文 100% 非空,这就是它被标记为可为空(?)的原因,因此您提到的“解决方法”实际上会在 Activity 分离时导致异常。为避免它,不要将 ctx:Context 标记为 lateinit var 使其可为空 protected var ctx:Context? = null 并在每次使用时检查它的状态。

关于android - 在 Fragment 中获取 not null Context 的保证方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388014/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com