Search code examples
androidandroid-fragmentsbottomnavigationview

Navigation component with bottom navigation


I am working with navigation component and bottom navigation

val navController = indNavController(R.id.nav_host_fragment)
bottom_navigation.inflateMenu(R.menu.bottom_navigation_menu)
bottom_navigation.setupWithNavController(navController)

and I am facing the next issue:

When an item is selected in the bottom navigation, then a fragment is loaded. The problem comes when I press again the same item, then a new fragment will be loaded, which it does not make sense at all.

Example: 1- User selects menu item A, then FragmentA is loaded. 2- User selects again menu item A, then a new FragmentA will be loaded,

I was trying to use

bottom_navigation.setOnNavigationItemSelectedListener {  }

But then the bottom navigation will not work with the navController.

So the question is: there is a way to handle this situation in order to load again a new fragment when the user is in that screen already?


Solution

  • Finally, I was able to fix this issue.

    As I said before, this code:

    bottom_navigation.setupWithNavController(navController)
    

    is using

    bottom_navigation.setOnNavigationItemSelectedListener {  }
    

    so every time I select / reselect an item, the navController will load a new fragment. I checked the javadoc for setOnNavigationItemSelectedListener() and it says:

    Set a listener that will be notified when a bottom navigation item is selected. This listener * will also be notified when the currently selected item is reselected, unless an {@link * OnNavigationItemReselectedListener} has also been set.

    So what I did is to add the next line to my code:

    bottom_navigation.setOnNavigationItemReselectedListener { }
    

    and that's all. The navController will load a fragment when an item is selected but not when an item is reselected in the bottom navigation.