我有一个底部导航视图,可在3个片段之间导航。我在add()
到FragmentTransaction
上遇到了问题,并且已经解决了,但我真的不明白为什么。
这是我的错误代码:
private fun showFragment(fragment : Fragment ,fragmentName :String) {
val transaction = manager.beginTransaction()
val currentFragment = manager.primaryNavigationFragment
if (currentFragment != null) {
transaction.hide(currentFragment)
}
val fragmentTemp = manager.findFragmentByTag(fragmentName)
if (fragmentTemp == null){
Log.d("ac1001","adding fragment (${fragment.tag})")
transaction.add(R.id.fragmentHolder,fragment,fragmentName)
} else {
transaction.show(fragmentTemp)
}
transaction.setPrimaryNavigationFragment(fragmentTemp)
transaction.setReorderingAllowed(true)
transaction.commitNowAllowingStateLoss()
}
这是我如何解决的问题:
private fun showFragment(fragment : Fragment ,fragmentName :String) {
val transaction = manager.beginTransaction()
val currentFragment = manager.primaryNavigationFragment
if (currentFragment != null) {
transaction.hide(currentFragment)
}
var fragmentTemp = manager.findFragmentByTag(fragmentName)
if (fragmentTemp == null){
fragmentTemp = fragment
Log.d("ac1001","adding fragment (${fragmentTemp})")
transaction.add(R.id.fragmentHolder,fragmentTemp,fragmentName)
} else {
transaction.show(fragmentTemp)
}
transaction.setPrimaryNavigationFragment(fragmentTemp)
transaction.setReorderingAllowed(true)
transaction.commitNowAllowingStateLoss()
}
这是我如何调用函数
showFragment(GroceryFragment(),GroceryFragment().javaClass.simpleName)
在我的第一个错误代码中,Log.d将返回null作为片段标记
在我的第二个固定代码中,Log.d返回正确的片段,一切正常。
我只需要澄清为什么会发生这种情况,因为我不了解这两个代码之间的区别。