我用A,B,C的三个按钮完成了BottomNavigationView。触摸B或C后,旋转屏幕将返回A。
我已经尝试过如下所示:
private fun bottomNavView() {
bottom_nav_view.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.navigation_home -> selectedFragment = HomeFragment.newInstance()
R.id.navigation_add_photos -> selectedFragment = AddPhotosFragment.newInstance()
R.id.navigation_profile -> selectedFragment = ProfileFragment.newInstance()
}
savedState =
supportFragmentManager.saveFragmentInstanceState(selectedFragment)!!
vm.setStateOfRotate(savedState)
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, selectedFragment)
.commit()
true
}
上面会出现如下错误:
java.lang.IllegalStateException: Fragment AddPhotosFragment{e1f2f47 (8c74a7e8-3af7-4290-be4a-f16f8ea6229f)} is not currently in the FragmentManager
at androidx.fragment.app.FragmentManagerImpl.saveFragmentInstanceState(FragmentManagerImpl.java:442)
at com.squall.searchdesigner.MainActivity$bottomNavView$1.onNavigationItemSelected(MainActivity.kt:92)
92线表示↓
savedState = supportFragmentManager.saveFragmentInstanceState(selectedFragment)!!
================================================== =======
private fun bottomNavView() {
bottom_nav_view.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.navigation_home -> selectedFragment = HomeFragment.newInstance()
R.id.navigation_add_photos -> selectedFragment = AddPhotosFragment.newInstance()
R.id.navigation_profile -> selectedFragment = ProfileFragment.newInstance()
}
vm.setStateOfRotate(savedState)
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, selectedFragment)
.commit()
savedState =
supportFragmentManager.saveFragmentInstanceState(selectedFragment)!!
true
}
}
但是,如果让:
savedState = supportFragmentManager.saveFragmentInstanceState(selectedFragment)!!
放在下面的下面
supportFragmentManager.beginTransaction()。replace(R.id.nav_host_fragment,selectedFragment).commit()
savedState变为null。
savedState = null
问题是什么?
最佳答案
后来,我解决了使用伴侣对象存储所选片段的问题,如下所示:
companion object{
var selectedFragment: Fragment? = null
}