Home > database >  onNavigationItemSelected is not called when the selected menu item is same
onNavigationItemSelected is not called when the selected menu item is same

Time:03-02

I have a simple BottomNavigationView with two menu items (Home Fragment, Settings Fragment) in an activity.

I have implemented onNavigationItemSelectedListener and onNavigationItemSelected.

Also bottomNavigationView.setOnNavigationItemSelectedListener(this);

App page lands on the Home Fragment.

onNavigationItemSelected is being called when I switch between menu items but When I first launch the app and tap on the same menu Item i.e. Home Fragment, onNavigationItemSelected is not being called.

I would need to show a toast whenever the user clicks on the home page when user is already in home page but onNavigationItemSelected event is not triggered.

CodePudding user response:

in mainActivity XML in FragmentContainerView add
android:name="Fragment.HomeFragment"

            <androidx.fragment.app.FragmentContainerView
                android:id="@ id/fragment_container"
                android:name="Fragment.HomeFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@id/bottom_navigation" />

then goto main activity onCreatemethod

  bottom_navigation.setOnNavigationItemSelectedListener {
   
        when (it.itemId) {
    
            R.id.menuHome_id -> {
               val bpfragment = HomeFragment()
                supportFragmentManager.beginTransaction().replace(R.id.fragment_container, bpfragment).commit()
            }
            R.id.menuSetting_id -> {
                val bpfragment = SettingsFragment()
                supportFragmentManager.beginTransaction().replace(R.id.fragment_container, bpfragment).commit()
            }

        }
        true
    }

still problem give your code of container, bottom navigation and transaction code. it will be easier to solve if you provide code too.

CodePudding user response:

First of all we do this in the MainActivity

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int v = item.getItemId();
        if(v==R.id.home)
        {
            getSupportActionBar().setTitle("Home");
            Fragment fragment = new HomeFragment();
            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction().replace(R.id.frame_layout, fragment).commit();
        }
        else if (v==R.id.dash_board)
        {
            getSupportActionBar().setTitle("Dashboard");
            Fragment fragment = new DashboardFragment();
            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction().replace(R.id.frame_layout, fragment).commit();
        }
   return true;
    }
};

This is a example here If you want to know in detail then click here

  • Related