Issue
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()
}
Answered By - Marat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.