Search code examples
androidandroid-fragmentsandroid-architecture-navigation

How to listen to Fragment Change in Navigation Component?


How can I add Fragment Change Listener in new Navigation Component?

I have a BottomNavigationView in which I used new Navigation Component following official sample

I have four destinations in my BottomNavigationView, all of them have their navigation graphs.

val navGraphIds = listOf(R.navigation.nav_home, R.navigation.nav_discover, R.navigation.nav_search, R.navigation.nav_my)

val controller = bottom_nav.setupWithNavController(
    navGraphIds = navGraphIds,
    fragmentManager = supportFragmentManager,
    containerId = R.id.navHostContainer,
    intent = intent
)

controller.observe(this, Observer { navController ->
    setupActionBarWithNavController(navController)
})

I want to have a listener in my MainActivity when fragment changed in any of 4 navigation graphs.

the controller is only affective when switching between BottomNavigationView destinations.


Solution

  • Have you tried NavController.OnDestinationChangedListener?

    private lateinit var controller: NavController // don't forget to initialize
    
    private val listener = NavController.OnDestinationChangedListener { controller, destination, arguments ->
        // react on change
        // you can check destination.id or destination.label and act based on that
    }
    
    override fun onResume() {
        super.onResume()
        controller.addOnDestinationChangedListener(listener)
    }
    
    override fun onPause() {
        controller.removeOnDestinationChangedListener(listener)
        super.onPause()
    }