Issue
Can the image of a NavigationBarItem
icon be changed whenever the NavigationBarItem
is selected or unselected?
Current result
Expected result
sealed class BottomNavItem(var title: String, var icon: ImageVector, var screen_route: String){
object Users: BottomNavItem("Users", Icons.Filled.AccountBox,"users")
object Notifications: BottomNavItem("Notifications", Icons.Filled.Notifications,"notifications")
}
items.forEach { item ->
NavigationBarItem(
icon = { Image(imageVector = item.icon, contentDescription = item.title) },
label = { Text(text = item.title) },
alwaysShowLabel = true,
selected = currentRoute == item.screen_route,
onClick = {
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {saveState = true}
}
launchSingleTop = true
restoreState = true
}
}
)
}
Solution
You should replace parameter icon:ImageVector
of class BottomNavView
to two parameters: iconFilled:ImageVector
and iconOutlined:ImageVector
.
sealed class BottomNavItem(var title: String, var filledIcon: ImageVector,var outlinedIcon:ImageVector, var screen_route: String){
object Users: BottomNavItem("Users", Icons.Filled.AccountBox,"users")
object Notifications: BottomNavItem("Notifications", Icons.Filled.Notifications,"notifications")
}
You will use iconFilled
for selected menu item and iconOutlined
for all unselected items. So replace foreach loop with this code:
items.forEach { item ->
val selected = currentRoute == item.screen_route
NavigationBarItem(
icon = { Image(imageVector = if(selected) item.filledIcon else item.outLinedIcon, contentDescription = item.title) },
label = { Text(text = item.title) },
alwaysShowLabel = true,
selected = selected,
onClick = {
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {saveState = true}
}
launchSingleTop = true
restoreState = true
}
}
)
}
Answered By - Brambora0
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.