使用分段式按钮让用户并排从一组选项中进行选择。分段式按钮有两种类型
- 单选按钮:让用户选择一个选项。
- 多选按钮:让用户选择两到五个项目。对于更复杂的选择或超过五个项目,请使用标签。

API 界面
使用 SingleChoiceSegmentedButtonRow
和 MultiChoiceSegmentedButtonRow
布局来创建分段式按钮。这些布局确保 SegmentedButton
s 的位置和大小正确,并共享以下关键参数
space
:调整按钮之间的重叠量。content
:包含分段式按钮行的内容,通常是连续的SegmentedButton
。
创建单选分段式按钮
此示例展示了如何创建单选分段式按钮
@Composable fun SingleChoiceSegmentedButton(modifier: Modifier = Modifier) { var selectedIndex by remember { mutableIntStateOf(0) } val options = listOf("Day", "Month", "Week") SingleChoiceSegmentedButtonRow { options.forEachIndexed { index, label -> SegmentedButton( shape = SegmentedButtonDefaults.itemShape( index = index, count = options.size ), onClick = { selectedIndex = index }, selected = index == selectedIndex, label = { Text(label) } ) } } }
代码要点
- 使用
remember
和mutableIntStateOf
初始化selectedIndex
变量,以跟踪选定的按钮索引。 - 定义一个
options
列表,表示按钮标签。 SingleChoiceSegmentedButtonRow
确保只能选择一个按钮。- 在
forEachIndexed
循环中为每个选项创建一个SegmentedButton
shape
使用SegmentedButtonDefaults.itemShape
根据其索引和选项总数定义按钮的形状。onClick
使用点击按钮的索引更新selectedIndex
。selected
根据selectedIndex
设置按钮的选择状态。label
使用Text
可组合项显示按钮标签。
结果

创建多选分段式按钮
此示例展示了如何创建带图标的多选分段式按钮,让用户选择多个选项
@Composable fun MultiChoiceSegmentedButton(modifier: Modifier = Modifier) { val selectedOptions = remember { mutableStateListOf(false, false, false) } val options = listOf("Walk", "Ride", "Drive") MultiChoiceSegmentedButtonRow { options.forEachIndexed { index, label -> SegmentedButton( shape = SegmentedButtonDefaults.itemShape( index = index, count = options.size ), checked = selectedOptions[index], onCheckedChange = { selectedOptions[index] = !selectedOptions[index] }, icon = { SegmentedButtonDefaults.Icon(selectedOptions[index]) }, label = { when (label) { "Walk" -> Icon( imageVector = Icons.AutoMirrored.Filled.DirectionsWalk, contentDescription = "Directions Walk" ) "Ride" -> Icon( imageVector = Icons.Default.DirectionsBus, contentDescription = "Directions Bus" ) "Drive" -> Icon( imageVector = Icons.Default.DirectionsCar, contentDescription = "Directions Car" ) } } ) } } }
代码要点
- 代码使用
remember
和mutableStateListOf
初始化selectedOptions
变量。这会跟踪每个按钮的选中状态。 - 代码使用
MultiChoiceSegmentedButtonRow
来包含按钮。 - 在
forEachIndexed
循环内部,代码为每个选项创建一个SegmentedButton
shape
根据其索引和选项总数定义按钮的形状。checked
根据selectedOptions
中的相应值设置按钮的选中状态。onCheckedChange
在点击按钮时,切换selectedOptions
中相应项目的选中状态。icon
根据SegmentedButtonDefaults.Icon
和按钮的选中状态显示图标。label
使用带有适当图像矢量和内容说明的Icon
可组合项显示与标签对应的图标。
结果

其他资源
- Material 3: 分段式按钮