I am trying to change the button background color on click of that button in Android jetpack compose.
With 1.0.0-beta02
you can use the MutableInteractionSource
and the collectIsPressedAsState()
property.
Something like:
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"
)
}
}
You can do it like this using 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 }) {
}
}
For a situation where your color changes back when you release your button, try this:
@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
}
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With