gpt4 book ai didi

android - 为什么支持FragmentManager.saveFragmentInstanceState(selectedFragment)!! = 空

转载 作者:行者123 更新时间:2023-11-30 04:54:13 28 4
gpt4 key购买 nike

我用 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

问题是什么?

最佳答案

后来,我解决了使用伴生对象存储选定 fragment 的问题,如下所示:

companion object{
var selectedFragment: Fragment? = null

}

关于android - 为什么支持FragmentManager.saveFragmentInstanceState(selectedFragment)!! = 空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507551/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com