如何在新的导航组件中添加片段更改侦听器?
我有一个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
个目的地之间切换时有效。
答案 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)
}