How to change button background color on click?

17.7k views Asked by At

How do I change the background color of a button on click?

3

There are 3 answers

5
Code Poet On BEST ANSWER

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
        }
    )
}
0
SalutonMondo 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
Gabriele Mariotti 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"
        )
    }
}

enter image description here

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")
}

enter image description here