jetpack compose 底部导航栏
时间: 2023-08-05 14:08:58 浏览: 179
在 Jetpack Compose 中创建底部导航栏可以使用 `BottomNavigation` 和 `BottomNavigationItem` 组件。以下是创建底部导航栏的步骤:
1. 导入所需的组件:
```kotlin
import androidx.compose.foundation.Icon
import androidx.compose.foundation.layout.Row
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.IconToggleButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
```
2. 创建底部导航栏的选项卡:
```kotlin
sealed class BottomNavItem(val route: String, val icon: ImageVector, val title: String) {
object Home : BottomNavItem("home", Icons.Filled.Home, "Home")
object Search : BottomNavItem("search", Icons.Filled.Search, "Search")
object Profile : BottomNavItem("profile", Icons.Filled.Person, "Profile")
}
val bottomNavItems = listOf(
BottomNavItem.Home,
BottomNavItem.Search,
BottomNavItem.Profile
)
```
3. 创建底部导航栏:
```kotlin
@Composable
fun BottomNavigationBar(
navController: NavHostController
) {
var selectedTab by remember { mutableStateOf(BottomNavItem.Home) }
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
bottomNavItems.forEach { screen ->
BottomNavigationItem(
icon = { Icon(screen.icon, contentDescription = null) },
label = { Text(screen.title) },
selected = currentRoute == screen.route,
onClick = {
selectedTab = screen
navController.navigate(screen.route) {
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
}
)
}
}
}
```
在 `BottomNavigationBar` 中,我们首先定义了一个 `selectedTab` 变量,用于跟踪当前选中的选项卡。然后,我们使用 `BottomNavigation` 组件创建底部导航栏,并使用 `BottomNavigationItem` 组件创建每个选项卡。我们使用 `navController` 控制导航,在点击选项卡时,更新 `selectedTab` 变量,然后导航到对应的目的地。
最后,我们可以将 `BottomNavigationBar` 组件添加到 `Scaffold` 中,创建一个带有底部导航栏的应用程序界面。
阅读全文