how do I change the background color of a button o...
# compose-desktop
d
how do I change the background color of a button on mouse over?
a
You can either use an
Indication
or just change the background on pointer enter/exit events:
Copy code
@OptIn(ExperimentalComposeUiApi::class)
fun main() = singleWindowApplication {
    var background by remember { mutableStateOf(Color.Blue) }
    Button(
        onClick = { },
        colors = ButtonDefaults.buttonColors(
            backgroundColor = background
        ),
        modifier = Modifier
            .onPointerEvent(PointerEventType.Enter) {
                background = Color.Red
            }
            .onPointerEvent(PointerEventType.Exit) {
                background = Color.Blue
            }
    ) {
        Text("Button")
    }
}
d
@Alexander Maryanovsky thanks! that's exactly what I was looking for
l
If the button exposes an InteractionSource parameter you can just do interactionSource.collectIsHoveredAsState() and directly use that
a
Indeed, like this:
Copy code
fun main() = singleWindowApplication {
    val interactionSource = remember { MutableInteractionSource() }
    val isHovered by interactionSource.collectIsHoveredAsState()
    val background = if (isHovered) Color.Red else Color.Blue
    Button(
        onClick = { },
        interactionSource = interactionSource,
        colors = ButtonDefaults.buttonColors(
            backgroundColor = background
        ),
    ) {
        Text("Button")
    }
}
l
And if you don't have one, you can use Modifier.hoverable instead of a custom pointer input to drive the event