如何更改点击按钮的背景颜色?
如果您只想在按下
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
}
)
}
在jetpack compose中,这样的效果应该通过使用interactionResource来实现,这是一个简单的例子。
@Composable
fun MyButton(){
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val bgcolor = if (isPressed) Color.Red else Color.White
val borderColor = if (isPressed) Color.White else Color.Red
OutlinedButton(
onClick = {
}, modifier = Modifier
.fillMaxWidth()
.height(40.dp),
shape = RoundedCornerShape(8.dp),
border = BorderStroke(1.dp, borderColor),
interactionSource = interactionSource,
colors = ButtonDefaults.outlinedButtonColors(backgroundColor = bgcolor)
) {
Text(text = "button", color=borderColor)
}
}