Home > Software design >  BottomNavigationView with setOnItemSelectedListener()
BottomNavigationView with setOnItemSelectedListener()

Time:12-26

I am trying to build app with BottomNavigationView and I set setOnItemSelectedListener() method to bottom navigation so I can do what I want when user select one of the menu in bottom navigation.

everything is good when I don't set setOnItemSelectedListener(), but when I set setOnItemSelectedListener() method then the fragment is not updated automatically when user select the bottom navigation menu.

I consider if that do i have to handle fragment transaction manually when I set this method?

thanks ^^

CodePudding user response:

Yes. You need to manually replace the fragment item on onNavigationItemSelected

Example:

private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // By using switch we can easily get
            // the selected fragment
            // by using there id.
            Fragment selectedFragment = null;
            switch (item.getItemId()) {
                case R.id.algorithm:
                    selectedFragment = new AlgorithmFragment();
                    break;
                case R.id.course:
                    selectedFragment = new CourseFragment();
                    break;
                case R.id.profile:
                    selectedFragment = new ProfileFragment();
                    break;
            }
            // It will help to replace the 
              // one fragment to other.
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, selectedFragment)
                    .commit();
            return true;
        }
    };

You can find a good tutorial here: https://www.geeksforgeeks.org/bottomnavigationview-inandroid/

  • Related