Gab*_*tti 44

如果您只想在按下 时更改背景颜色,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"
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果你想实现一个切换按钮,你可以使用类似的东西:

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")
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Cod*_*oet 24

您可以使用 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 }) {

    }
}
Run Code Online (Sandbox Code Playgroud)

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

@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
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,我已经为这种情况添加了一个解决方案。 (3认同)
  • 这与我正在寻找的很接近。但当按钮单击释放事件发生时,颜色应保留为默认值。 (2认同)