在多个片段之间切换时保存片段的状态
我目前有以下简单的片段代码:
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
}
如果我切换到另一个片段,我想保存它的当前状态并在返回时恢复它。我怎样才能做到这一点?
我不想保存一些变量,而是保存整个片段状态。
我通过下面的代码调用该片段:
navView.setNavigationItemSelectedListener {
// Highlight the current selected Item in NavBar
it.isChecked = true
// Switch Fragments when user clicks on Items in NavDrawer
when(it.itemId) {
R.id.nav_home -> replaceFragment(HomeFragment(), it.title.toString())
R.id.nav_import -> replaceFragment(ImportFragment(), it.title.toString())
R.id.nav_export -> replaceFragment(ExportFragment(), it.title.toString())
R.id.nav_share -> replaceFragment(ShareFragment(), it.title.toString())
}
true
}
// Default Page is Home
replaceFragment(HomeFragment(), getString(R.string.home))
I currently have the following simple fragment code:
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
}
In case I switch to another Fragment I want to save it's current state and restore it when moving back. How can I do that?
I don't want save some variables, but the whole fragment state.
I'm calling the fragment through the code below:
navView.setNavigationItemSelectedListener {
// Highlight the current selected Item in NavBar
it.isChecked = true
// Switch Fragments when user clicks on Items in NavDrawer
when(it.itemId) {
R.id.nav_home -> replaceFragment(HomeFragment(), it.title.toString())
R.id.nav_import -> replaceFragment(ImportFragment(), it.title.toString())
R.id.nav_export -> replaceFragment(ExportFragment(), it.title.toString())
R.id.nav_share -> replaceFragment(ShareFragment(), it.title.toString())
}
true
}
// Default Page is Home
replaceFragment(HomeFragment(), getString(R.string.home))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论