Home > Net >  Material 3 NavigationBarItem: How to change selected and unselected icons?
Material 3 NavigationBarItem: How to change selected and unselected icons?

Time:07-11

Can the image of a NavigationBarItem icon be changed whenever the NavigationBarItem is selected or unselected?

Current result

enter image description here

Expected result

enter image description here

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
            }
        }
    )
}

CodePudding user response:

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
            }
        }
    )
}
  • Related