Switch

Functions summary

Unit
@Composable
Switch(
    checked: Boolean,
    onCheckedChange: ((Boolean) -> Unit)?,
    modifier: Modifier,
    enabled: Boolean,
    interactionSource: MutableInteractionSource?,
    colors: SwitchColors
)

Material Design switch

Cmn

Functions

Switch

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

Material Design switch

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

Switches
image

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.unit.dp

val checkedState = remember { mutableStateOf(true) }
Switch(checked = checkedState.value, onCheckedChange = { checkedState.value = it })

var pineappleOnPizza by remember { mutableStateOf(true) }

Row(
    Modifier.padding(16.dp)
        .toggleable(
            role = Role.Switch,
            value = pineappleOnPizza,
            onValueChange = { pineappleOnPizza = it },
        )
) {
    Switch(checked = pineappleOnPizza, onCheckedChange = null)
    Spacer(Modifier.width(8.dp))
    Text("Pineapple on pizza?")
}
Parameters
checked: Boolean

whether or not this component is checked

onCheckedChange: ((Boolean) -> Unit)?

callback to be invoked when Switch is being clicked, therefore the change of checked state is requested. If null, then this is passive and relies entirely on a higher-level component to control the "checked" state.

modifier: Modifier = Modifier

Modifier to be applied to the switch layout

enabled: Boolean = true

whether the component is enabled or grayed out

interactionSource: MutableInteractionSource? = null

an optional hoisted MutableInteractionSource for observing and emitting Interactions 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.

colors: SwitchColors = SwitchDefaults.colors()

SwitchColors that will be used to determine the color of the thumb and track in different states. See SwitchDefaults.colors.