5

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

4

2 回答 2

9

1.0.0-beta02你可以使用和MutableInteractionSource属性collectIsPressedAsState()

就像是:

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"
        )
    }
}
于 2021-03-20T18:22:07.897 回答
8

你可以这样做使用 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
        }
    )
}
于 2021-02-04T15:45:48.390 回答