如何解决如何在点击按钮时更改按钮背景颜色
我正在尝试在 Android jetpack compose 中单击该按钮时更改按钮背景颜色。
解决方法
你可以像这样使用 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
}
)
}
,
通过 1.0.0-beta02
,您可以使用 MutableInteractionSource
和 collectIsPressedAsState()
属性。
类似于:
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
// Use the state to change our UI
val color = if (isPressed) Color.Blue else Color.Yellow
Column() {
Button(
onClick = {},interactionSource = interactionSource,colors= ButtonDefaults.buttonColors(backgroundColor = color)
){
Text(
"Button"
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。