如何在点击按钮时更改按钮背景颜色

问题描述

我正在尝试在 Android jetpack compose 中单击该按钮时更改按钮背景颜色。

解决方法

你可以像这样使用 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 }) {

    }
}

对于释放按钮时颜色变回的情况,请尝试以下操作:

@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
        }
    )
}
,

通过 1.0.0-beta02,您可以使用 MutableInteractionSourcecollectIsPressedAsState() 属性。

类似于:

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