Search code examples
androidkotlinandroid-jetpackandroid-jetpack-navigation

Prevent navigating to the same fragment


I'm using Android navigation jetpack library with BottomNavigationView. I have implemented the NavHost, the NavGraph and my fragments. Everything is working as intented when I use actions to navigate.

I use the following code to setup everything:

 val navController = Navigation.findNavController(this, R.id.nav_host)
 bottom_navigation.setupWithNavController(navController)

The problem is that if I click a tab 2 times the fragment is recreated twice. Is there any way to intercept navigation? I don't want to navigate to the same fragment that's being shown.


Solution

  • As per this issue,

    Feel free to set a OnNavigationItemReselectedListener, which takes precedence over the OnNavigationItemSelectedListener set by NavigationUI.

    val navController = Navigation.findNavController(this, R.id.nav_host)
    bottom_navigation.setupWithNavController(navController)
    bottom_navigation.setOnNavigationItemReselectedListener {
      // Do nothing to ignore the reselection
    }