BottomNavigationView +导航到不同选项卡时保存片段状态

问题描述 投票:0回答:1

我将BottomNavigationView用于底部的标签。

1)选项卡1-从服务器获取数据并显示到RecyclerView2)标签2-从服务器获取URL并加载Webview3)标签3-从服务器获取数据并显示到RecyclerView4)标签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 savedInstanceStateonCreateView方法的参数),并像第四个选项卡一样恢复状态?3)为什么前三个标签不能自动恢复状态?

android android-fragments bottomnavigationview android-design-library
1个回答
0
投票

您现在正在做的是用这段代码替换片段

getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.container_fragment, fragment, tag)
        .commit();

虽然您可以添加片段而不是像下面的代码那样替换它们

getSupportFragmentManager()
        .beginTransaction()
        .add(R.id.container_fragment, fragment, tag)
        .commit();

此操作将添加片段而不是替换片段,因此将保存片段状态。

© www.soinside.com 2019 - 2024. All rights reserved.