我有一个片段容器,可以显示当前片段。当按下后退按钮时,我想删除最上面的片段,但当它是第一个片段时,我想在后台移动应用程序。(否则,我的主要片段也会被删除。)
所以我的(Kotlin)代码看起来是这样的:
override fun onBackPressed() {
...
when (supportFragmentManager.backStackEntryCount) {
1 -> {
moveTaskToBack(true)
}
else -> {
super.onBackPressed()
//supportFragmentManager.popBackStackImmediate()
}
}
只有一个例外。当我启动应用程序并显示第二个片段时,我按下后退按钮两次(快速)。这样,顶部碎片开始被移除,但第二次背压随后直接开始(顶部碎片没有完全移除)。
我还尝试使用supportFragmentManager。PopBackbackImmediate()代替,但它也不起作用。
所以我有两个问题:
----编辑1----
我注意到只有在替换片段时设置事务动画时才会发生这种情况。因此,如果我在添加碎片时(而不是在反压时)删除该行,它似乎会起作用:
ft.setCustomAnimations(R.anim.enter_from_bottom, R.anim.exit_to_top,
R.anim.enter_from_top, R.anim.exit_to_bottom)
----编辑2----
当在这里使用这段代码时,它也可以工作(只是区别在于它也删除了第一个(底部)片段)。但显然,原生Android方法似乎可以避免这个问题。
super.onBackPressed() // Remove bottom fragement
super.onBackPressed() // No more fragments -> move App into background
----这就是“创建”片段的方式----
val ft = supportFragmentManager.beginTransaction()
ft.setCustomAnimations(R.anim.enter_from_bottom, R.anim.exit_to_top,
R.anim.enter_from_top, R.anim.exit_to_bottom)
ft.replace(R.id.fragmentContainer, fragment, fragment::class.java.simpleName)
.addToBackStack(fragment::class.java.simpleName)
.commitAllowingStateLoss()
下面是重叠片段的屏幕截图: