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

Kotlin中含伴生对象的Fragment如何销毁?切换时remove报错解决

问题原因与解决办法

错误的核心是remove()方法要求传入Fragment的实例对象,但你直接传了MyFragment——在Kotlin里,直接访问类名会默认指向它的伴生对象,导致类型不匹配,才出现Required: Fragment! Found: MyFragment.Companion的提示,和伴生对象本身的存在无关,只是传参错误。

正确的销毁方式

你需要持有要移除的Fragment的实例引用,而非类或伴生对象:

  1. 在Activity中声明变量保存当前显示的Fragment实例:
private var currentFragment: Fragment? = null
  1. 初始化Fragment时,用你的伴生对象创建实例并赋值给该变量:
// 假设你的伴生对象提供了newInstance()方法创建实例
val myFragment = MyFragment.newInstance()
currentFragment = myFragment
supportFragmentManager.beginTransaction()
    .add(R.id.fragment_container, myFragment)
    .commitAllowingStateLoss()
  1. 切换Fragment时,通过这个实例调用remove:
currentFragment?.let {
    supportFragmentManager.beginTransaction()
        .remove(it)
        .commitAllowingStateLoss()
}
// 再添加新的Fragment实例
val newFragment = AnotherFragment.newInstance()
currentFragment = newFragment
supportFragmentManager.beginTransaction()
    .add(R.id.fragment_container, newFragment)
    .commitAllowingStateLoss()

更简洁的替代方案:使用replace

如果你的需求是切换Fragment(移除旧的,添加新的),可以直接用replace()方法,它会自动完成移除旧Fragment、添加新Fragment的操作,无需手动调用remove:

val newFragment = AnotherFragment.newInstance()
supportFragmentManager.beginTransaction()
    .replace(R.id.fragment_container, newFragment)
    .commitAllowingStateLoss()
currentFragment = newFragment

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:15:23