导航栏与抽屉 (Nav Components)
M3 提供了一套完整的导航组件体系,适用于不同尺寸的屏幕。
1. 底部导航栏 (NavigationBar)
替代了 M2 的 BottomNavigation。通常用于移动端,展示 3-5 个顶级目的地。
kotlin
var selectedItem by remember { mutableIntStateOf(0) }
val items = listOf("首页", "音乐", "我的")
val icons = listOf(Icons.Filled.Home, Icons.Filled.MusicNote, Icons.Filled.Person)
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
icon = { Icon(icons[index], contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index },
// M3 特性:选中时的指示器颜色
colors = NavigationBarItemDefaults.colors(
indicatorColor = MaterialTheme.colorScheme.secondaryContainer
)
)
}
}2. 侧边导航栏 (NavigationRail)
适用于平板电脑或横屏手机,位于屏幕左侧。
kotlin
NavigationRail {
// 顶部的 FAB(可选)
FloatingActionButton(onClick = { }) {
Icon(Icons.Filled.Add, "Add")
}
Spacer(Modifier.height(16.dp))
// 导航项
items.forEachIndexed { index, item ->
NavigationRailItem(
icon = { Icon(icons[index], contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}3. 侧滑抽屉 (NavigationDrawer)
M3 提供了三种类型的抽屉:
- ModalNavigationDrawer: 模态抽屉,默认隐藏,滑出时遮挡内容(手机常用)。
- DismissibleNavigationDrawer: 永久抽屉的变体,可通过操作隐藏/显示(平板常用)。
- PermanentNavigationDrawer: 永久固定显示(桌面/大屏常用)。
模态抽屉 (Modal)
kotlin
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
ModalDrawerSheet {
Text("应用标题", modifier = Modifier.padding(16.dp))
HorizontalDivider()
NavigationDrawerItem(
label = { Text("首页") },
selected = true,
onClick = { /* 关闭抽屉并导航 */
scope.launch { drawerState.close() }
}
)
// ... 其他项
}
}
) {
// 主要内容区域
Scaffold(
topBar = {
TopAppBar(
title = { Text("首页") },
navigationIcon = {
IconButton(onClick = { scope.launch { drawerState.open() } }) {
Icon(Icons.Default.Menu, null)
}
}
)
}
) { innerPadding ->
// Content
}
}抽屉内容
ModalDrawerSheet 是 M3 提供的标准抽屉容器,它自带了正确的圆角、宽度和背景色。