Home > Back-end >  How to switch baseline and outline icons in navigation bar compose?
How to switch baseline and outline icons in navigation bar compose?

Time:12-26

So I wanna switch between a baseline version and an outline version of the icon when selected in bottom navigation Material Design 3, I have this compose bottomBar:

NavigationBar {
    items.forEachIndexed{ index, screen ->
        NavigationBarItem(
            icon =  { Icon(painterResource(id = screen.icon), contentDescription = screen.label) },
            label = { Text(screen.label) },
            selected = selectedItem == index,
            onClick = {
                selectedItem = index
                navController.navigate(screen.route){
                    popUpTo(navController.graph.findStartDestination().id)
                    launchSingleTop = true
                    restoreState = true
                }

            }
        )
    }
}

And these screen objects:

sealed class Screen(val route: String, val label: String, val icon: Int) {
    object Home : Screen("home", "Home", R.drawable.outline_home_black_24)
    object History : Screen("history", "History", R.drawable.outline_history_black_24)
}

how to switch between R.drawable.outline_home and R.drawable.baseline_home when selected?

CodePudding user response:

You can store needed images inside Screen, like this:

sealed class Screen(val route: String, val label: String, val icon: Int, val iconSelected: Int) {
    object Home : Screen("home", "Home", R.drawable.outline_home_black_24, R.drawable.baseline_home_black_24)
    object History : Screen("history", "History", R.drawable.outline_history_black_24, R.drawable.baseline_home_black_24)
}

Then select an icon depending on selection state:

icon = {
    Icon(
        painterResource(
            id = if (selectedItem == index) screen.iconSelected else screen.icon
        ),
        contentDescription = screen.label
    )
},
  • Related