Reputation: 1479
How do I change the background color of a button on click?
Upvotes: 26
Views: 21913
Reputation: 8013
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
}
)
}
Upvotes: 26
Reputation: 709
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)
}
}
Upvotes: 2
Reputation: 364730
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")
}
Upvotes: 52