How do we track bottom menu nav items clicks only when bottom menu items are clicked and still use setupWithNavController ? Currently using Bottom navigation view 2.4.0-alpha05, we have a use case for tracking bottom nav clicks for analytics and bottom nav is set like below
binding.bottomNavigationView.setupWithNavController(navController)
If I use below, then bottom nav selection stops working.
binding.bottomNavigationView.setOnItemSelectedListener {
//track clicks
true
}
An Alternative to this to copy the source code NavigationUi.setupWithNavController
and alter it like below however I'm not sure if this has repercussions, say for example if google adds improvement or changes setupWithNavController later, then the project will miss that change :
private fun setupWithNavController(
navigationBarView: NavigationBarView,
navController: NavController,
onItemSelected: ((Int) -> Unit)
) {
navigationBarView.setOnItemSelectedListener { item ->
onItemSelected.invoke(item.itemId)
NavigationUI.onNavDestinationSelected(
item,
navController
)
}
val weakReference = WeakReference(navigationBarView)
navController.addOnDestinationChangedListener(
object : NavController.OnDestinationChangedListener {
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
val view = weakReference.get()
if (view == null) {
navController.removeOnDestinationChangedListener(this)
return
}
view.menu.forEach { item ->
if (destination.matchDestination(item.itemId)) {
item.isChecked = true
}
}
}
})
}