如何收听导航组件中的片段更改?

时间:2019-05-24 00:20:51

标签: android android-fragments android-architecture-navigation

如何在新的导航组件中添加片段更改侦听器?

我有一个BottomNavigationView,其中在official sample之后使用了新的导航组件

我的BottomNavigationView中有四个目的地,所有目的地都有其导航图。

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)
})

当4个导航图中的任何一个片段发生变化时,我都希望MainActivity中有一个侦听器。

controller仅在BottomNavigationView个目的地之间切换时有效。

1 个答案:

答案 0 :(得分:1)

您尝试使用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() {
    super.onPause()
    controller.removeOnDestinationChangedListener(listener)
}