Gab*_*tti 44
如果您只想在按下 时更改背景颜色,Button您可以使用MutableInteractionSource和collectIsPressedAsState()属性。
就像是:
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)
| 归档时间: |
|
| 查看次数: |
17088 次 |
| 最近记录: |