Skip to content

Instantly share code, notes, and snippets.

@pengj
Last active September 16, 2021 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pengj/e38186c34163ff6c73996ef1dbe93391 to your computer and use it in GitHub Desktop.
Save pengj/e38186c34163ff6c73996ef1dbe93391 to your computer and use it in GitHub Desktop.
Create Bottom navigation with Jetpack Compose
@Composable
fun MainScreen() {
val navController = rememberNavController()
Scaffold(
bottomBar = { BottomNav(navController) }
) {
Navigation(navController = navController)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun BottomNav(navController: NavController) {
val items = NavigationItem.values()
BottomNavigation {
val navBackStackEntry = navController.currentBackStackEntry
val currentRouteId = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = { NavItemIcon(item) },
label = { Text(stringResource(id = item.title)) },
selected = currentRouteId == item.routeID,
onClick = {
navController.navigate(item.routeID)
}
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun NavItemIcon(item: NavigationItem) {
if (item.count == 0) {
Icon(
painter = painterResource(id = item.icon),
contentDescription = stringResource(id = item.title)
)
} else {
BadgeBox(badgeContent = { Text(item.count.toString()) }) {
Icon(
painter = painterResource(id = item.icon),
contentDescription = stringResource(id = item.title)
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment