Jetpack Compose:选择器组件
一、Checkbox
复选框,代码如下所示:
val checkState = remember { mutableStateOf(false) }
Checkbox(
checked = checkState.value,
onCheckedChange = { checkState.value = it}
)
二、TriStateCheckbox
三态选择框,代码如下所示:
// 为 Checkbox 定义状态
val (state, OnStateChange) = remember { mutableStateOf(true) }
val (state2, OnStateChange2) = remember { mutableStateOf(false) }
// 根据 CheckBox 状态来设置 TriStateCheckbox 状态
val parentState = remember(state, state2) {
if (state && state2) ToggleableState.On
else if (!state && !state2) ToggleableState.Off
else ToggleableState.Indeterminate
}
TriStateCheckbox(
state = parentState,
onClick = {
val result = (parentState != ToggleableState.On)
OnStateChange(result)
OnStateChange2(result)
}
)
Column {
Checkbox(checked = state, onCheckedChange = OnStateChange)
Checkbox(checked = state2, onCheckedChange = OnStateChange2)
}
三、Switch
单选开关,代码如下所示:
var checkState by remember { mutableStateOf(false) }
Switch(
checked = checkState,
onCheckedChange = {
checkState = it
}
)
四、Slider
滑动开关,代码如下所示:
var sliderPosition by remember { mutableStateOf(0f) }
Slider(
value = sliderPosition,
onValueChange = {
sliderPosition = it
}
)