Home > Blockchain >  How to share click event for Switch and its container without recreation
How to share click event for Switch and its container without recreation

Time:06-17

I have created a clickable Row containing a Switch to replicate a settings option. How can I ensure that the Switch gets checked/unchecked whenever I click the Row rather than specifically just the Switch control?

@Composable
fun ComposableSettingSimpleMode() {
    val isChecked = remember { mutableStateOf(false) }

    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable(onClick = {})) {
        Text(text = stringResource(id = R.string.colour_blind))
        Switch(checked = isChecked.value, onCheckedChange = {
            isChecked.value = it
        })
    }
}

CodePudding user response:

I think this is what you want...

@Composable
fun ComposableSettingColourBlind() {
    // this variable will disable the action to change the state
    // without greyed out the component.
    var yourEnableLogic = false 
    var isChecked by remember { mutableStateOf(true) }
    val onChange by rememberUpdatedState { checked: Boolean ->
        if (yourEnableLogic) { // if is enable, we can change the state
            isChecked = checked
        }
    }
    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable(onClick = { onChange(!isChecked) })
    ) {
        Text(text = "Bla")
        Switch(checked = isChecked, onCheckedChange = onChange)
    }
}
  • Related