我尝试使用commitNow
来确保片段事务是同步的。但是,经过我的测试,我发现由于某种原因,commitNow
不会立即删除碎片。
我添加了一个延迟 100 毫秒的处理程序,但片段仍然不为空。之后,我将postDelayed
更改为 1000 毫秒,最后,片段为空。
如何确保片段在调用commitNow
后立即为空?我试图添加supportFragmentManager.popBackStack()
,但没有帮助。
如果无法立即使片段为 null,如何在添加相同片段之前检查该片段是否不再在堆栈中?
更新我发现如果我删除setCustomAnimations
,那么交易确实会立即发生。如何观察setCustomAnimations
何时完成?
val fragment = supportFragmentManager.findFragmentByTag(DEMO_FRAGMENT)
if (fragment != null) {
Log.d("test", "DEMO_FRAGMENT is not null")
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.setCustomAnimations(R.anim.custom_fade_in, R.anim.custom_fade_out)
.remove(fragment).commitNow()
supportFragmentManager.popBackStack();
Log.d("test", "is fragment null:${supportFragmentManager.findFragmentByTag(DEMO_FRAGMENT) == null}")
Handler().postDelayed({
Log.d("test", "is fragment null:${supportFragmentManager.findFragmentByTag(DEMO_FRAGMENT) == null}")
}, 1000)
}
}
为此,您必须使用popBackStackImmediate()
.更多信息在这里