Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 527
musooff Avatar asked May 24 '19 00:05

musooff


People also ask

Can we use navigation component for activity?

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.


1 Answers

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()
}
like image 197
Marat Avatar answered Oct 29 '22 21:10

Marat