Reputation: 33
First, the code:
data class Destination (
val title: String,
val icon: ImageVector,
val route: String
)
@Composable
fun ExperimentWithBackButtonPress(
modifier: Modifier = Modifier,
) {
val listOfDestinations = listOf (
Destination ("Home Screen", Icons.Default.Home, "home_screen"),
Destination ("Settings Screen", Icons.Default.Settings, "settings_screen"),
)
var currentSelection by remember { mutableStateOf(listOfDestinations[0])}
val navController = rememberNavController()
Scaffold(
modifier = modifier,
bottomBar = {
NavigationBar {
listOfDestinations.forEach { destination ->
NavigationBarItem(
selected = currentSelection == destination,
onClick = {
navController.navigate(destination.route) {
popUpTo(listOfDestinations[0].route) {
inclusive = false
}
}
currentSelection = destination
},
icon = {
Icon(
imageVector = destination.icon,
contentDescription = destination.title
)
},
label = {
Text(text = destination.title)
}
)
}
}
}
) {innerPadding ->
Box(
modifier = modifier.padding(innerPadding)
) {
NavHost(
navController = navController,
startDestination = listOfDestinations[0].route
) {
composable(listOfDestinations[0].route) {
ScreenTemplate(
label = listOfDestinations[0].title,
modifier = modifier
)
}
composable(listOfDestinations[1].route) {
ScreenTemplate(
label = listOfDestinations[1].title,
modifier = modifier
)
}
}
}
}
}
@Composable
fun ScreenTemplate(
modifier: Modifier = Modifier,
label: String,
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier.fillMaxSize()
) {
Text(
modifier = modifier,
text = label,
style = MaterialTheme.typography.headlineMedium
)
}
}
What is the issue?
After navigating from one screen to another - and after that when I press back button - the screen navigates to NavigationDestinations.Reference as expected. BUT, the icon in the NavigationBar is still highlighted for the Navigation.Interpolation screen - meaning it doen't change with back button press.
How do I address that?
I don't understand how to handle Backpress event and sync that with the selection procedure.
Upvotes: 0
Views: 64