我正在尝试在 Android Jetpack Compose 中单击该按钮时更改按钮背景颜色。
如果您只想在按下
Button
时更改背景颜色,您可以使用MutableInteractionSource
和collectIsPressedAsState()
属性。
类似的东西:
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
// Use the state to change the background color
val color = if (isPressed) Color.Blue else Color.Yellow
Column() {
Button(
onClick = {},
interactionSource = interactionSource,
colors= ButtonDefaults.buttonColors(backgroundColor = color)
){
Text(
"Button"
)
}
}
如果你想实现一个切换按钮,你可以使用类似的东西:
var selected by remember { mutableStateOf(false) }
val color = if (selected) Color.Blue else Color.Yellow
Button(
onClick = { selected = !selected },
colors= ButtonDefaults.buttonColors(backgroundColor = color)
){
Text("Button")
}
你可以使用 1.0.0-alpha11 这样做
@Composable
fun ButtonColor() {
val selected = remember { mutableStateOf(false) }
Button(colors = ButtonDefaults.buttonColors(
backgroundColor = if (selected.value) Color.Blue else Color.Gray),
onClick = { selected.value = !selected.value }) {
}
}
对于松开按钮时颜色变回的情况,试试这个:
@Composable
fun ButtonColor() {
val color = remember { mutableStateOf(Color.Blue) }
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = color.value
),
onClick = {},
content = {},
modifier = Modifier.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
color.value = Color.Yellow }
MotionEvent.ACTION_UP -> {
color.value = Color.Blue }
}
true
}
)
}