我使用BottomNavigationView
作为底部选项卡。
1( 选项卡1-从服务器获取数据并显示到RecyclerView
2(选项卡2-从服务器中获取URL并加载Webview
3(选项卡3-从服务器获得数据并显示给RecyclerView
4(选项卡4-使用PreferenceFragmentCompat
设置屏幕
为了在用户切换选项卡时保存这些片段的状态,我使用了来自这个博客的以下代码
将Fragment.SavedState
保存到SparseArray<Fragment.SavedState>
Fragment.State currentFragmentState = getSupportFragmentManager().saveFragmentInstanceState(currentFragment)
当用户导航回以前的选项卡时,再次恢复状态
fragment.setInitialSavedState(savedState)
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container_fragment, fragment, tag)
.commit();
我看到的是,只有Tab 4(带PreferenceFragmentCompat
的设置屏幕(保持状态——如果我向下滚动到第10个项目,并在导航到其他片段后再次回到设置屏幕,我会看到顶部的第10个位置。
然而,前三个选项卡再次进行web服务调用,所有内容都被重新加载。此外,我可以看到,对于前三个选项卡,onCreateView
方法的Bundle savedInstanceState
参数也不为空。
我的问题是
1(PreferenceFragmentCompat
(第4个选项卡(如何自动恢复状态
2(如何在前三个选项卡中使用非空Bundle savedInstanceState
(onCreateView
方法的参数(,并像第四个选项卡那样恢复状态
3(为什么前三个选项卡没有自动恢复状态?
编辑
我正在使用与博客相同的代码。
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_item_1:
swapFragments(new Fragment1(), item.getItemId(), TAG_1);
return true;
case R.id.navigation_item_2:
swapFragments(new Fragment2(), item.getItemId(), TAG_2);
return true;
case R.id.navigation_item_3:
swapFragments(new Fragment3(), item.getItemId(), TAG_3);
return true;
case R.id.navigation_item_4:
swapFragments(new Fragment4(), item.getItemId(), TAG_4);
return true;
default:
return false;
}
}
});
private void swapFragments(Fragment fragment, int itemId, String tag) {
if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
saveFragmentState(itemId, tag);
createFragment(fragment, itemId, tag);
}
}
private void saveFragmentState(int itemId, String tag) {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container_fragment);
if (currentFragment != null) {
fragmentStateArray.put(currentSelectedItemId, getSupportFragmentManager().saveFragmentInstanceState(currentFragment));
}
currentSelectedItemId = itemId;
}
private void createFragment(Fragment fragment, int itemId, String tag) {
fragment.setInitialSavedState(fragmentStateArray.get(itemId));
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container_fragment, fragment, tag)
.commit();
}
您现在所做的是用以下代码重新放置片段
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container_fragment, fragment, tag)
.commit();
而你可以添加片段,而不是像下面的代码那样替换它们
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container_fragment, fragment, tag)
.commit();
这样做的目的是添加片段,而不是替换它,因此片段状态将被保存。
尝试移动onCreate
方法中前3个片段的获取操作。
原因是当您再次输入片段时,onActivityCreated
会被调用并再次获取数据,然后更新recyclerview,它会重置并将您移回recyclerview的开始位置。
但如果您将其称为onCreate
,那么提取数据应该只在您第一次输入片段时发生,因此它不会更新recyclerview,也不会重置它