Android 导航底部片段重叠

Android Navigation Bottom Fragments overlapping

我在我的应用程序中使用了带有 4 个项目的导航底部,所以我有 4 个片段。 第一个片段(主页)包含一个 recyclerView,其他片段不包含任何 recyclerView。

问题就在这里;
当我导航到其他片段时,我可以在后台看到回收站视图。 当我导航回第一个片段时,在原始视图下有另一个回收器视图!

我用过这个: fm.beginTransaction().hide(active).show(fragment2).commit();
但是 hide() 方法不起作用。


这是我的代码的相关部分:

I have globally defined these

final Fragment fragment1 = new HomeFragment();
final Fragment fragment2 = new AddFragment();
final Fragment fragment3 = new CalendarFragment();
final Fragment fragment4 = new ProfileFragment();
final FragmentManager fm = getSupportFragmentManager();
Fragment active = fragment1;

然后

In the onCreate :

fm.beginTransaction().add(R.id.nav_host_fragment, fragment4, "4").hide(fragment4).commit();
fm.beginTransaction().add(R.id.nav_host_fragment, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.nav_host_fragment, fragment2, "2").hide(fragment2).commit();
fm.beginTransaction().add(R.id.nav_host_fragment, fragment1, "1").commit();

最后

the navigation item listener :

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    if (active == fragment1)
                        return false;
                    fm.beginTransaction().hide(active).show(fragment1).commit();
                    active = fragment1;
                    return true;
                case R.id.navigation_add:
                    if (active == fragment2)
                        return false;
                    fm.beginTransaction().hide(active).show(fragment2).commit();
                    active = fragment2;
                    return true;
                case R.id.navigation_calendar:
                    if (active == fragment3)
                        return false;
                    fm.beginTransaction().hide(active).show(fragment3).commit();
                    active = fragment3;
                    return true;
                case R.id.navigation_profile:
                    if (active == fragment4)
                        return false;
                    fm.beginTransaction().hide(active).show(fragment4).commit();
                    active = fragment4;
                    return true;
            }
            return false;
        }
    };

我之前在 XML 文件的片段中使用了 navGraph,但我忘记删除 navGraph,所以它在后台显示 navGraph 中的第一个片段。