FragmentTransaction 隐藏/显示有时不起作用 [英] FragmentTransaction hide/show doesn't work sometimes
问题描述
我有一个带有底部导航选项卡的活动,这些选项卡正在更改其中的片段.当我在这些选项卡上来回单击时,它会在某些时候停止工作.代码执行得很好,因为我在其中放入了一些日志.但是片段没有被切换.
I have an activity with bottom navigation tabs that are changing the fragments in it. When I click back and forth on those tabs, at some point it stops working. Code executes just fine as I put some logs in it. But the fragments aren't being switched.
代码在 kotlin 中,但相当简单
Code is in kotlin but it's rather straight forward
fun showTabFragment(tag: String) {
val currentFragment: Fragment? = supportFragmentManager.fragments?.lastOrNull()
var fragment = supportFragmentManager.findFragmentByTag(tag)
val fragmentExists = fragment != null
if (fragment == null) {
when (tag) {
TAG_LOGBOOK -> fragment = LogbookFragment()
TAG_RECIPES -> fragment = RecipesFragment()
TAG_PROFILE -> fragment = ProfileFragment()
else -> fragment = MeetingPlacesFragment()
}
}
val transaction = supportFragmentManager.beginTransaction()
if (currentFragment != null) {
Log.i("jacek", "hiding " + currentFragment.javaClass.simpleName)
transaction.hide(currentFragment)
}
if (fragmentExists) {
Log.i("jacek", "showing " + fragment.javaClass.simpleName)
transaction.show(fragment)
} else {
Log.i("jacek", "adding " + fragment.javaClass.simpleName)
transaction.add(R.id.container, fragment, tag)
}
transaction.commit()
}
碎片很重.我会尝试一些轻量级的,但在我看来这应该不是问题.还有什么我可以尝试的吗?
The fragments are quite heavy. I will try with some lightweight ones, but still that shouldn't be a problem in my opinion. Is there anything else I could try?
我使用的是最新的支持库 - 25.2.0此外,我对替换片段不感兴趣,因为重点是添加淡入淡出动画而不重新创建它们
I'm using the latest support library - 25.2.0 Also I'm not interested in replacing the fragments as the point is to add crossfade animation without recreating them
推荐答案
您需要重复使用要隐藏或显示的片段的同一个实例.
You need to reuse the same instance of a fragment that you wanted to hide or show.
private fun replaceFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().apply {
if (fragment.isAdded) {
show(fragment)
} else {
add(R.id.fmFragmentContainer, fragment)
}
supportFragmentManager.fragments.forEach {
if (it != fragment && it.isAdded) {
hide(it)
}
}
}.commit()
}
这篇关于FragmentTransaction 隐藏/显示有时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!