Android导航底部片段重叠

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

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

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

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


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

我已经全局定义了这些

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;

然后

在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();

以及最后

导航项目侦听器:

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;
        }
    };
android android-fragments navigation
1个回答
0
投票

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

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