Switch

[Switch] provides an animated switch for use as a toggle control in [ToggleChip] or [SplitToggleChip].

Installation

This component is available for Jetpack Compose (Android)

dependencies {
   implementation("androidx.wear.compose:compose-material:1.4.0-alpha08")
}

Overloads

@Composable
fun Switch(
    checked: Boolean,
    modifier: Modifier = Modifier,
    colors: SwitchColors = SwitchDefaults.colors(),
    enabled: Boolean = true,
    onCheckedChange: ((Boolean) -> Unit)? = null,
    interactionSource: MutableInteractionSource? = null,
)

Parameters

namedescription
checkedBoolean flag indicating whether this switch is currently toggled on.
modifierModifier to be applied to the switch. This can be used to provide a content description for accessibility.
colors[SwitchColors] from which the colors of the thumb and track will be obtained.
enabledBoolean flag indicating the enabled state of the [Switch] (affects the color).
onCheckedChangeCallback to be invoked when Switch is clicked. If null, then this is passive and relies entirely on a higher-level component to control the state (such as [ToggleChip] or [SplitToggleChip]).
interactionSourceWhen also providing [onCheckedChange], an optional hoisted [MutableInteractionSource] for observing and emitting [Interaction]s for this switch. You can use this to change the switch's appearance or preview the switch in different states. Note that if null is provided, interactions will still happen internally.

Code Example

ToggleChipWithSwitch

@Composable
fun ToggleChipWithSwitch() {
    var checked by remember { mutableStateOf(true) }
    // The primary label should have a maximum 3 lines of text
    // and the secondary label should have max 2 lines of text.
    ToggleChip(
        label = {
            Text("SwitchIcon", maxLines = 3, overflow = TextOverflow.Ellipsis)
        },
        secondaryLabel = {
            Text("With secondary label", maxLines = 2, overflow = TextOverflow.Ellipsis)
        },
        checked = checked,
        // For Switch  toggle controls the Wear Material UX guidance is to set the
        // unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
        // rather than the default.
        colors = ToggleChipDefaults.toggleChipColors(
            uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
        ),
        toggleControl = {
            Switch(
                checked = checked,
                enabled = true,
            )
        },
        onCheckedChange = { checked = it },
        appIcon = {
            Icon(
                painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
                contentDescription = "airplane",
                modifier = Modifier.size(24.dp).wrapContentSize(align = Alignment.Center),
            )
        },
        enabled = true,
    )
}
Previous ComponentSwipeToRevealChip
Next ComponentText