How do I change the background color of a button on click?
How to change button background color on click?
17.7k views Asked by SoftwareGuy At
3
There are 3 answers
0
On
In jetpack compose such an effect should implemented by using interactionResource here's a simple example.
@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)
}
}
3
On
If you want to change the background color only when the Button
is pressed 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 the background color
val color = if (isPressed) Color.Blue else Color.Yellow
Column() {
Button(
onClick = {},
interactionSource = interactionSource,
colors= ButtonDefaults.buttonColors(backgroundColor = color)
){
Text(
"Button"
)
}
}
If you want to achieve a toggle button you can use something like:
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")
}
You can do it like this using versions 1.0.0 and later:
For a situation where your color changes back when you release your button, try this: