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

软件人

我正在尝试在 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
        }
    )
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章