Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change Button Background color on click of the button

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

like image 411
SoftwareGuy Avatar asked Feb 04 '21 15:02

SoftwareGuy


Video Answer


2 Answers

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"
        )
    }
}
like image 84
Gabriele Mariotti Avatar answered Oct 01 '22 00:10

Gabriele Mariotti


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
        }
    )
}
like image 41
Code Poet Avatar answered Oct 01 '22 02:10

Code Poet