I'm using Jetpack Compose and androidx-navigation-compose.
Generally, I like the save/restore state mechanism when switching between bottom navigation tabs.
However, if I'm in a detail screen of a particular tab and I click on the tab again I wnat the app to navigate to the respective top level destination of that tab - opposed to doing nothing. How can I achieve this behavior?
The behavior I described is not implemented in Now-in-Android. However, it used to be the default behavior when setting up a Bottom Bar with androidx navigation - before Compose.
I tried to built a minimal example, which can be found here.
Here is the most relevant part:
Scaffold(
modifier = Modifier.fillMaxSize(),
bottomBar = {
NavigationBar {
bottomBarItems.forEach { item ->
val screen = item.screen
NavigationBarItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
label = { Text(item.title) },
selected = screen == currentTopLevelDestination.screen,
onClick = {
navController.navigate(screen.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
}
) { paddingValues ->
NavHost(
navController = navController,
startDestination = TopLevelDestination.HOME.route,
modifier = Modifier.padding(paddingValues)
) {
navigation(
route = TopLevelDestination.HOME.route,
startDestination = Screen.Home.route,
) {
composable(Screen.Home.route) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
) {
Button(onClick = { navController.navigate(Screen.HomeDetail.route) }) {
Text("Go to Home Detail")
}
}
}
composable(Screen.HomeDetail.route) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
) {
Text("Home Detail")
}
}
}
navigation(
route = TopLevelDestination.MORE.route,
startDestination = Screen.More.route,
) {
composable(Screen.More.route) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
) {
Button(onClick = { navController.navigate(Screen.MoreDetail.route) }) {
Text("Go to More Detail")
}
}
}
composable(Screen.MoreDetail.route) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
) {
Text("More Detail")
}
}
}
}
}
What I want is the following behavior:
- App starts in Home screen
- Navigate to Home Detail
- Tap on Home bottom navigation item
-> I want to go back to Home