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

22
如何在点击时更改按钮的背景颜色?
3个回答

42

如果您只想在按下 Button 时更改背景颜色,可以使用 MutableInteractionSourcecollectIsPressedAsState() 属性。

像这样:

val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()

// Use the state to change the background color
val color = if (isPressed) Color.Blue else Color.Yellow

Column() {
    Button(
        onClick = {},
        interactionSource = interactionSource,
        colors= ButtonDefaults.buttonColors(backgroundColor = color)
    ){
        Text(
         "Button"
        )
    }
}

在此输入图片描述

如果你想要实现一个切换按钮,可以使用以下代码:

var selected by remember { mutableStateOf(false) }
val color = if (selected) Color.Blue else Color.Yellow

Button(
    onClick = { selected = !selected },
    colors= ButtonDefaults.buttonColors(backgroundColor = color)
    ){
        Text("Button")
}

输入图片说明


这个问题有点挑剔,如果按钮在可滚动的容器中,它不会随着非常快的点击而改变颜色,因为这个问题的修复:https://issuetracker.google.com/issues/203141462 - Gak2
1
这真是疯狂,竟然没有一个简单的参数像colorOnTouchDown那样。 - J. Doe

22
你可以这样做,使用1.0.0版本及更高版本:
@Composable
fun ButtonColor() {

    val selected by remember { mutableStateOf(false) }

    Button(colors = ButtonDefaults.buttonColors(
            backgroundColor = if (selected) Color.Blue else Color.Gray),

            onClick = { selected = !selected }) {

    }
}

如果你的按钮松开后颜色会恢复原样的情况,可以尝试以下方法:
@Composable
fun ButtonColor() {

    val color by remember { mutableStateOf(Color.Blue) }

    Button(
        colors = ButtonDefaults.buttonColors(
            backgroundColor = color
        ),

        onClick = {},

        content = {},

        modifier = Modifier.pointerInteropFilter {
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    color = Color.Yellow }

                MotionEvent.ACTION_UP  -> {
                    color = Color.Blue }
            }
            true
        }
    )
}

2
这很接近我想要的。但是当按钮点击释放事件发生时,颜色应该恢复为默认值。 - SoftwareGuy
3
好的,我已经为那种情况添加了一个解决方案。 - Code Poet
1
应该使用 by 而不是 =,这样就可以跳过每次使用 .value - kc_dev
我编辑了答案,并将=改为by - undefined
好的,谢谢,我也把所有的 .value 都删除了,这样就不会引起混淆了。 - undefined

0
在Jetpack Compose中,应该通过使用interactionResource来实现这样的效果。下面是一个简单的示例。
@Composable
fun MyButton(){
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val bgcolor = if (isPressed) Color.Red else Color.White
val borderColor = if (isPressed) Color.White else Color.Red

OutlinedButton(
    onClick = {
    }, modifier = Modifier
        .fillMaxWidth()
        .height(40.dp),
    shape = RoundedCornerShape(8.dp),
    border = BorderStroke(1.dp, borderColor),
    interactionSource = interactionSource,
    colors = ButtonDefaults.outlinedButtonColors(backgroundColor = bgcolor)
) {
    Text(text = "button", color=borderColor)
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接