Kotlin中含伴生对象的Fragment如何销毁?切换时remove报错解决
问题原因与解决办法
错误的核心是remove()方法要求传入Fragment的实例对象,但你直接传了MyFragment——在Kotlin里,直接访问类名会默认指向它的伴生对象,导致类型不匹配,才出现Required: Fragment! Found: MyFragment.Companion的提示,和伴生对象本身的存在无关,只是传参错误。
正确的销毁方式
你需要持有要移除的Fragment的实例引用,而非类或伴生对象:
- 在Activity中声明变量保存当前显示的Fragment实例:
private var currentFragment: Fragment? = null
- 初始化Fragment时,用你的伴生对象创建实例并赋值给该变量:
// 假设你的伴生对象提供了newInstance()方法创建实例 val myFragment = MyFragment.newInstance() currentFragment = myFragment supportFragmentManager.beginTransaction() .add(R.id.fragment_container, myFragment) .commitAllowingStateLoss()
- 切换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 -
相关产品推荐
相关产品推荐

