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

从BottomSheetDialogFragment打开另一个同类型弹窗提示未附加怎么解决

错误原因

你遇到的报错本质是调用时序问题:
Dialog1中调用show(childFragmentManager, tag)加载Dialog2后立刻执行了dismiss(),此时Dialog2还没完成和childFragmentManager的附着流程,Dialog1就被销毁,其持有的childFragmentManager同步失效,Dialog2找不到合法的宿主Fragment就会抛出has not been attached yet异常。

修复方案

根据你的业务需求可以选择两种方案:

方案1:切换Dialog2的宿主(推荐,实现最简单)

如果你的需求是弹出Dialog2的同时关闭Dialog1,直接将加载Dialog2的FragmentManager替换为外层的父级FragmentManager即可,修改Dialog1的点击逻辑:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  binding.primaryButton.setOnClickListener {
    Dialog2().apply {
      // 此处替换为父级FragmentManager,也可使用requireActivity().supportFragmentManager
      show(parentFragmentManager, tag)
    }
    dismiss()
  }
}

该方案下Dialog2的宿主是外层Activity/父Fragment,不会受到Dialog1销毁的影响。

方案2:调整Dialog1的销毁时机

如果你需要Dialog2依附于Dialog1加载,只需要等Dialog2完成附着流程后再销毁Dialog1即可:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  binding.primaryButton.setOnClickListener {
    val dialog2 = Dialog2()
    dialog2.show(childFragmentManager, tag)
    // 等待Fragment事务执行完成,确认Dialog2已附着
    childFragmentManager.executePendingTransactions()
    // 监听Dialog2生命周期,显示完成后再销毁Dialog1
    dialog2.lifecycle.addObserver(object : DefaultLifecycleObserver {
      override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        dismiss()
        dialog2.lifecycle.removeObserver(this)
      }
    })
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:09:02