- 在 build.gradle 文件中添加依赖项:
dependencies {
implementation "androidx.navigation:navigation-compose:$nav_version"
}
- 在 Composable 函数中设置导航栏:
@Composable
fun BottomNavigation() {
val navController = rememberNavController()
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
BottomNavigationItem(
icon = { Icon(Icons.Filled.Home, contentDescription = "Home") },
label = { Text("Home") },
selected = currentRoute == "home",
onClick = {
navController.navigate("home") {
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
}
)
BottomNavigationItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = "Favorite") },
label = { Text("Favorite") },
selected = currentRoute == "favorite",
onClick = {
navController.navigate("favorite") {
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
}
)
BottomNavigationItem(
icon = { Icon(Icons.Filled.Settings, contentDescription = "Settings") },
label = { Text("Settings") },
selected = currentRoute == "settings",
onClick = {
navController.navigate("settings") {
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
}
)
}
}
- 在 NavHost 中设置底部导航栏:
NavHost(
navController = navController,
startDestination = "home"
) {
composable("home") { HomeScreen() }
composable("favorite") { FavoriteScreen() }
composable("settings") { SettingsScreen() }
}
BottomNavigation()