Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabled but clickable switch in jetpack compose

I have a disabled switch but I still want it to be clickable. I tried to add a clickable modifier but it still won't register the click when the switch itself is pressed

Switch(
    modifier = Modifier
        .clickable(
            enabled = myBool,
            onClick = onSwitch,
            indication = null,
            interactionSource = remember { MutableInteractionSource() },
        )
        .constrainAs(actionButton) {
            top.linkTo(text.top)
            end.linkTo(parent.end)
        },
    interactionSource = interactionSource,
    checked = switchChecked,
    enabled = if (myBool) false else actionButtonEnabled,
    onSwitch = onSwitch,
)

How can I make it clickable as if it was enabled?

like image 472
Tiberiu Paduraru Avatar asked Oct 15 '25 08:10

Tiberiu Paduraru


1 Answers

I assume your switch includes a label. Therefore, you should have a click handler for the entire row that the label and switch appear on. This is a good UX design because many users may not exactly tap on the switch. You need to place the label and switch inside a box and have a separate container at a higher Z order be clickable (in this example a Row is used):

val checkedState = remember { mutableStateOf(true) }

Box(modifier = Modifier.fillMaxWidth().wrapContentHeight()) {
    Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
        Text("Activate Premium Features")

        Box(contentAlignment = Alignment.CenterEnd, modifier = Modifier.fillMaxWidth()) {
            Switch(
                checked = checkedState.value,
                onCheckedChange = {
                    checkedState.value = it
                },
                enabled = false
            )
        }
    }

    Row(modifier = Modifier.fillMaxWidth().requiredHeight(45.dp).clickable {
        // Do something
    }) {

    }
}
like image 145
Johann Avatar answered Oct 16 '25 23:10

Johann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!