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.
To take full advantage of the Navigation component, your app should use multiple fragments in a single activity. However, activities can still benefit from the Navigation component. Note, however, that your app's UI must be visually broken up across several navigation graphs.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With