该 Switch
组件允许用户在两种状态之间切换:选中和未选中。在您的应用中,您可以使用开关让用户执行以下操作之一:
- 切换设置的打开或关闭。
- 启用或禁用功能。
- 选择一个选项。
该组件包含两个部分:拇指和轨道。拇指是开关的可拖动部分,轨道是背景。用户可以将拇指向左或向右拖动以更改开关的状态。他们也可以点击开关来选中和取消选中。

基本实现
请参阅 Switch
参考以获取完整的 API 定义。以下是一些您可能需要使用的关键参数:
checked
:开关的初始状态。onCheckedChange
:当开关的状态发生变化时调用的回调函数。enabled
:开关是否启用。colors
:用于开关的颜色。
以下示例是 Switch
可组合组件的最小实现。
@Composable fun SwitchMinimalExample() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it } ) }
未选中时,此实现显示如下:

选中时,外观如下:

高级实现
实现更高级的开关时,您可能想要使用的主要参数如下:
thumbContent
:用于自定义选中时拇指的外观。colors
:用于自定义轨道和拇指的颜色。
自定义拇指
您可以为 thumbContent
参数传递任何可组合组件以创建自定义拇指。以下是使用自定义图标作为拇指的开关示例:
@Composable fun SwitchWithIconExample() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it }, thumbContent = if (checked) { { Icon( imageVector = Icons.Filled.Check, contentDescription = null, modifier = Modifier.size(SwitchDefaults.IconSize), ) } } else { null } ) }
在此实现中,未选中时的外观与上一节中的示例相同。但是,选中时,此实现显示如下:

自定义颜色
以下示例演示了如何使用 colors 参数更改开关的拇指和轨道的颜色,同时考虑开关是否已选中。
@Composable fun SwitchWithCustomColors() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it }, colors = SwitchDefaults.colors( checkedThumbColor = MaterialTheme.colorScheme.primary, checkedTrackColor = MaterialTheme.colorScheme.primaryContainer, uncheckedThumbColor = MaterialTheme.colorScheme.secondary, uncheckedTrackColor = MaterialTheme.colorScheme.secondaryContainer, ) ) }
此实现显示如下:
