我有框架布局。在 onCreate 方法中,我立即调用了 fragmentReplace() 方法并将 HomeFragment 传递给它。HomeFragment 包含 RecyclerView。当我通过 BottomNavigationView 切换到另一个片段并返回时,HomeFragment 中的所有内容都将被删除。
fragmentReplace() 方法
public void fragmentReplace(Fragment fragment) {
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
我曾经创建一个全局 View 并将 HomeFragment 传递给它,然后在需要时再次获取它。但我认为这不是正确的方法。在 Internet 上的文章中,我无法理解或找到我需要的信息。
如果 RecyclerView 存储在您在 HomeFragment.onCreateView 中创建 View 的标记中,那么当 HomeFragment 取消固定时,它会与创建的 View 一起被删除。当你再次附加fragment时,onCreateView又可以工作了,里面有一个RecyclerView,但是它是空的,你需要再次附加适配器。您可以在 onViewCreated、onStart 或 onResume 中执行此操作。阅读有关保存片段状态的信息,有几种方法,其中一种会帮助您。
好吧,到堆中,为了保持 RecyclerView 滚动,将 LayoutManager 拉出并保存它的状态,如下所示: