How can I setupWithNavController
my BottomNavigationView with a FloatingActionButton (FAB) on top?
Thanks StackOverflow for hating me and not letting me display photos. :)
According to the Navigation library releases…
Starting in Navigation 2.4.0-alpha01, the state of each menu item is saved and restored when you use
setupWithNavController
.
This works like a charm, however, when I setup my BottomNavigationView and press the FAB, the states of the current menu items are reloaded. How can I achieve the same behavior of clicking on any menu item with the FAB?
binding.activityMainBottomNavigationView.setupWithNavController(navController)
binding.activityMainFloatingActionButton.setOnClickListener {
// TODO: Fix navigation.
navController.navigate(R.id.homeFragment)
binding.activityMainBottomNavigationView.selectedItemId = R.id.homeFragment
}
As I understand, calling navController.navigate()
may be resetting the current nav_graph
used by the fragmentContainerView
and that's why the current menu items are being reloaded. Is there any way to avoid this?
After a week of several attempts, I achieved the desired purpose using onNavDestinationSelected
from NavigationUI
.
binding.activityMainBottomNavigationView.setupWithNavController(navController)
binding.activityMainFloatingActionButton.setOnClickListener {
NavigationUI.onNavDestinationSelected(
binding.activityMainBottomNavigationView.menu.findItem(R.id.homeFragment),
navController
)
binding.activityMainBottomNavigationView.selectedItemId = R.id.homeFragment
}
In this way, the states of the fragments and navigation survive! 🤠
Cheers! 🍾