How to replace new Fragment

how to replace fragment |

Step1:

 BottomNavigationView bnv;




Step2:-

in onCreate method

 bnv = findViewById(R.id.bottomnavigation);

 setMyFragment(new Home_Fragment());
            bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                    switch (item.getItemId()) {
                        case R.id.menu_home:
                            Home_Fragment homeFragment1 = new Home_Fragment();
                            replaceMyFragment(homeFragment1);
                            break;
                        case R.id.menu_book:
                            BookingFragment homeFragment2 = new BookingFragment();
                            replaceMyFragment(homeFragment2);
                            break;
                        case R.id.menu_profile:
                            Intent intent = new Intent(DashboadmainActivity.this, ProfileActivity.class);
                            startActivity(intent);
                            break;
                    }
                    return true;
                }
            });

Step3:-

Create these to methods

      private void setMyFragment(Fragment fragment) {
        //get current fragment manager
        FragmentManager fragmentManager = getSupportFragmentManager();

        //get fragment transaction
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //set new fragment in fragment_container (FrameLayout)
        fragmentTransaction.add(R.id.main_container, fragment);
        fragmentTransaction.commit();
    }

    private void replaceMyFragment(Fragment fragment) {
        //get current fragment manager
        FragmentManager fragmentManager = getSupportFragmentManager();

        //get fragment transaction
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //set new fragment in fragment_container (FrameLayout)
        fragmentTransaction.replace(R.id.main_container, fragment);
        fragmentTransaction.commit();
    }