0

Inside the DrawerLayout in FrameLayout when I click the item of Navigation Menu, they keep clashing and stacking over each other, so what do I do?

This is my Java code for loading fragment in the onNavigationItemSelected

Here the Frame Layout is called fragmentContainer.

  public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){

            case R.id.nav_profile:
                loadFragment(new ProfileFragment());
                
                break;

           case R.id.nav_logout:
                logoutPrompt();
                break;

            default:
                loadFragment(new HomeFragment());
                break;

        }
            drawerLayout.closeDrawer(GravityCompat.START);

        return true;
    }



    private void loadFragment(Fragment fragment) {


        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        transaction.add(R.id.fragment_container,fragment);
        transaction.commit();


    }

Any suggestion is appreciated.

I was expecting that the fragmentContainer(Frame Layout) wouldn't keep stacking, I first noticed this when the space between the recyclerView I could View another recyclerView of same information below it and scrolling.

Enowneb
  • 943
  • 1
  • 2
  • 11
Shubham
  • 1
  • 3

1 Answers1

0

In your loadFragment(), you are adding a new Fragment on top of your existing Fragments:

transaction.add(R.id.fragment_container,fragment);

If you do not want the Fragments to be stacked, you should use replace() instead:

transaction.replace(R.id.fragment_container,fragment);

You can refer to the official document for more details.

Enowneb
  • 943
  • 1
  • 2
  • 11