How do I change the background color of a button on click?
You can do it like this using versions 1.0.0 and later:
@Composable
fun ButtonColor() {
val selected by remember { mutableStateOf(false) }
Button(colors = ButtonDefaults.buttonColors(
backgroundColor = if (selected) Color.Blue else Color.Gray),
onClick = { selected = !selected }) {
}
}
For a situation where your color changes back when you release your button, try this:
@Composable
fun ButtonColor() {
val color by remember { mutableStateOf(Color.Blue) }
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = color
),
onClick = {},
content = {},
modifier = Modifier.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
color = Color.Yellow }
MotionEvent.ACTION_UP -> {
color = Color.Blue }
}
true
}
)
}