[英]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我试图添加一个clickable
修饰符,但当开关本身被按下时它仍然不会注册点击
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?如何使它可点击,就像它已启用一样?
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.这是一个很好的 UX 设计,因为许多用户可能不会完全点击开关。 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):您需要将标签和开关放在一个框内,并在更高的 Z 顺序中有一个单独的容器可点击(在本例中使用了 Row):
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
}) {
}
}
Passing paidUser
as true
will toggle the switch on clicking the Text
or Switch
.将paidUser
设为true
将在单击Text
或Switch
。
Passing paidUser
as false
will allow you to navigate to the required screen.将paidUser
设为false
将允许您导航到所需的屏幕。
@Composable
fun DisabledClickableSwitch1(
paidUser: Boolean,
) {
var checked by remember {
mutableStateOf(false)
}
val onCheckedChange = {
if (paidUser) {
checked = !checked
} else {
// Navigate to the require screen to show info about the paid feature here
Log.e("Test", "Navigate from here")
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.clickable {
onCheckedChange()
}
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text("Enable Paid Feature")
Switch(
checked = checked,
enabled = paidUser,
onCheckedChange = null,
)
}
}
The label Text
is optional.标签Text
是可选的。 Can be removed if not required.如果不需要,可以删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.