Skip to content

Instantly share code, notes, and snippets.

@Merkost
Last active July 17, 2024 00:23
Show Gist options
  • Save Merkost/dcad273c5dbf547177a72ad4debece08 to your computer and use it in GitHub Desktop.
Save Merkost/dcad273c5dbf547177a72ad4debece08 to your computer and use it in GitHub Desktop.
Simple BottomBar navigation in Jetpack Compose
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ComposeTypeSafeNavigationTheme {
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
Scaffold(
bottomBar = {
BottomAppBar {
BottomNavigation.entries
.forEachIndexed { index, navigationItem ->
val isSelected by remember(currentRoute) {
...
}
NavigationBarItem(
selected = isSelected,
label = { Text(navigationItem.label) },
icon = {
Icon(
navigationItem.icon,
contentDescription = navigationItem.label
)
},
onClick = {
navController.navigate(navigationItem.route)
}
)
}
}
}
) {
NavHost(
modifier = Modifier
.fillMaxSize()
.padding(it),
navController = navController,
startDestination = Destinations.HomeGraph
) {
navigation<Destinations.HomeGraph>(
startDestination = Destinations.Home,
) {
composable<Destinations.Home> {
Greeting("HomeScreen")
}
composable<Destinations.Search> {
Greeting("Search")
}
composable<Destinations.Profile> { backStackEntry ->
Greeting("Profile")
}
}
}
}
}
}
}
}
sealed class Destinations {
@Serializable
data object HomeGraph: Destinations()
@Serializable
data object Home : Destinations()
@Serializable
data class Search(val searchText: String? = null) : Destinations()
@Serializable
data object Profile : Destinations()
}
enum class BottomNavigation(val label: String, val icon: ImageVector, val route: Destinations) {
HOME("Home", Icons.Filled.Home, Destinations.Home),
SEARCH("Search", Icons.Filled.Search, Destinations.Search()),
PROFILE("Profile", Icons.Filled.AccountCircle, Destinations.Profile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment