New Compose Multiplatform components arrived on Composables UICheck it out →

Component in Material 3 Compose

Switch

Common

Switches toggle the state of a single item on or off.

Switch
image

Last updated:

Installation

dependencies {
   implementation("androidx.compose.material3:material3:1.3.0-beta04")
}

Overloads

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

Parameters

namedescription
checkedwhether or not this switch is checked
onCheckedChangecalled when this switch is clicked. If null, then this switch will not be interactable, unless something else handles its input events and updates its state.
modifierthe [Modifier] to be applied to this switch
thumbContentcontent that will be drawn inside the thumb, expected to measure [SwitchDefaults.IconSize]
enabledcontrols the enabled state of this switch. When false, this component will not respond to user input, and it will appear visually disabled and disabled to accessibility services.
colors[SwitchColors] that will be used to resolve the colors used for this switch in different states. See [SwitchDefaults.colors].
interactionSourcean 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 Examples

SwitchSample

@Composable
@Sampled
@Preview
fun SwitchSample() {
    var checked by remember { mutableStateOf(true) }
    Switch(
        modifier = Modifier.semantics { contentDescription = "Demo" },
        checked = checked,
        onCheckedChange = { checked = it }
    )
}

SwitchWithThumbIconSample

@Composable
@Sampled
@Preview
fun SwitchWithThumbIconSample() {
    var checked by remember { mutableStateOf(true) }

    Switch(
        modifier = Modifier.semantics { contentDescription = "Demo with icon" },
        checked = checked,
        onCheckedChange = { checked = it },
        thumbContent = {
            if (checked) {
                // Icon isn't focusable, no need for content description
                Icon(
                    imageVector = Icons.Filled.Check,
                    contentDescription = null,
                    modifier = Modifier.size(SwitchDefaults.IconSize),
                )
            }
        }
    )
}