我将BottomNavigationView
用于底部的标签。
1)选项卡1-从服务器获取数据并显示到RecyclerView
2)标签2-从服务器获取URL并加载Webview
3)标签3-从服务器获取数据并显示到RecyclerView
4)标签4-使用PreferenceFragmentCompat
为了在用户切换选项卡时保存这些片段的状态,我正在使用此blog中的以下代码
将Fragment.SavedState
保存到SparseArray<Fragment.SavedState>
Fragment.State currentFragmentState = getSupportFragmentManager().saveFragmentInstanceState(currentFragment)
[当用户导航回到上一个选项卡时再次恢复状态
fragment.setInitialSavedState(savedState)
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container_fragment, fragment, tag)
.commit();
[我看到的是只有选项卡4(带有PreferenceFragmentCompat
的设置屏幕)保持状态-如果我向下滚动到第十个项目并导航到其他片段后再次回到设置屏幕,我会看到第10个位置顶端。
但是,前三个选项卡再次进行Web服务调用,并且所有内容都重新加载。另外,我可以看到Bundle savedInstanceState
方法的onCreateView
参数对于前三个选项卡也不为空。
我的问题是
1] PreferenceFragmentCompat
(第四个选项卡)如何自动恢复状态?2)如何在前三个选项卡中使用非空Bundle savedInstanceState
(onCreateView
方法的参数),并像第四个选项卡一样恢复状态?3)为什么前三个标签不能自动恢复状态?
您现在正在做的是用这段代码替换片段
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container_fragment, fragment, tag)
.commit();
虽然您可以添加片段而不是像下面的代码那样替换它们
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container_fragment, fragment, tag)
.commit();
此操作将添加片段而不是替换片段,因此将保存片段状态。