I need to implement a switch with a label with Jetpack Compose and Material3.
My solution so far (it basically just extends the existing switch component and adds the label
property):
@Composable
fun LabeledSwitch(
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit)?,
modifier: Modifier = Modifier,
thumbContent: (@Composable () -> Unit)? = null,
enabled: Boolean = true,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
colors: SwitchColors = SwitchDefaults.colors(),
label: (@Composable () -> Unit),
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
label()
Switch(
checked = checked,
onCheckedChange = onCheckedChange,
thumbContent = thumbContent,
enabled = enabled,
interactionSource = interactionSource,
colors = colors
)
}
}
This correctly displays the label (e.g. {Text("Test")}
) next to the switch.
However, I would like to forward all click events on the label to the switch, so that you can touch the label to toggle the switch value.
It basically should work like the old <Switch>
component in XML layouts.
One idea I had was adding a modifier to the container like so:
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.then(Modifier
.clickable { onCheckedChange?.invoke(!checked) }
)
But this is not optimal as it shows a ripple effect on the whole item.
Is there any better solution? Maybe even without a custom component?