You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何调用requireContext()会抛出Fragment未关联上下文异常?

问题场景

我创建了名为HomeFragment的Fragment,编写了在其中显示DialogFragment的代码如下:

private fun showCustomDialog() {
    CustomDialog().apply {
        arguments = Bundle().apply {
            putString("title", requireContext().getString(R.string.app_name))
        }
    }.show(parentFragmentManager, "customDialog")
}

运行时抛出如下异常:

Fragment CustomDialog{1ef2304} (4ca006b2-19b7-4550-a227-e5c6d1d43e02) not attached to a context.

改用this@HomeFragment代替requireContext()则无异常,代码如下:

private fun showCustomDialog() {
    CustomDialog().apply {
        arguments = Bundle().apply {
            // 无异常抛出
            putString("title", this@HomeFragment.getString(R.string.app_name))
        }
    }.show(parentFragmentManager, "customDialog")
}

请问为何使用requireContext()时上下文为null?

原因分析
  • 作用域混淆导致上下文对象错误:在CustomDialog().apply{}代码块内,requireContext()默认指向的是刚创建的CustomDialog实例,而非HomeFragment。此时CustomDialog仅完成构造,还未执行onAttach()生命周期方法绑定上下文,调用requireContext()自然会抛出未绑定上下文的异常。
  • this@HomeFragment明确指定了正确的上下文持有者:this@HomeFragment直接指向已经完成生命周期初始化、绑定好上下文的HomeFragment实例,调用它的getString()方法可以正常获取资源,不会出现上下文为空的问题。
  • Fragment上下文的绑定时机:Fragment的上下文是在onAttach(Context)方法执行时才被赋值关联的,刚通过构造函数创建的Fragment实例还未进入生命周期流程,不存在绑定的上下文。

内容的提问来源于stack exchange,提问作者kuma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:25:33