如何在单击按钮时更改按钮背景颜色
How to Change Button Background color on click of the button
我正在尝试更改 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
您可以使用 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"
)
}
}
我正在尝试更改 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
您可以使用 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"
)
}
}