How to Change Button Background color on click of the button

Viewed 6155

I am trying to change the button background color on click of that button in Android jetpack compose.

2 Answers

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