如何检测 Jetpack Compose 中是否按下了按钮?
How to detect that a button is pressed in Jetpack Compose?
我尝试制作一个按钮,它具有这种很酷的效果,当点击时边框半径会发生变化(就像在 Android 12 默认计算器应用程序中一样),同时还保持按钮的涟漪效果。
我认为可行的是:
var pressed by remember { mutableStateOf(false) }
val borderRadius by animateDpAsState(
if (pressed) 10.0.dp
else 20.0.dp
)
val buttonTitle = "uniqueButton"
Button(
onClick = {
// some on click stuff
},
shape = RoundedCornerShape(borderRadius),
modifier = Modifier
.pointerInput(buttonTitle) {
detectTapGestures(
onPress = {
pressed = true
tryAwaitRelease()
pressed = false
}
)
}
) {
Text(text = buttonTitle)
}
但是传递给 onPress
的函数中的代码永远不会执行。
根据我的理解,应该是在点击或按下按钮时。我的错误在哪里,我是否误解了the documentation中的某些内容?
大多数 Compose 控件都具有用于此目的的 interactionSource
参数。使用方法如下:
val interactionSource = remember { MutableInteractionSource() }
val pressed by interactionSource.collectIsPressedAsState()
Button(
onClick = {},
interactionSource = interactionSource,
) {
}
我尝试制作一个按钮,它具有这种很酷的效果,当点击时边框半径会发生变化(就像在 Android 12 默认计算器应用程序中一样),同时还保持按钮的涟漪效果。
我认为可行的是:
var pressed by remember { mutableStateOf(false) }
val borderRadius by animateDpAsState(
if (pressed) 10.0.dp
else 20.0.dp
)
val buttonTitle = "uniqueButton"
Button(
onClick = {
// some on click stuff
},
shape = RoundedCornerShape(borderRadius),
modifier = Modifier
.pointerInput(buttonTitle) {
detectTapGestures(
onPress = {
pressed = true
tryAwaitRelease()
pressed = false
}
)
}
) {
Text(text = buttonTitle)
}
但是传递给 onPress
的函数中的代码永远不会执行。
根据我的理解,应该是在点击或按下按钮时。我的错误在哪里,我是否误解了the documentation中的某些内容?
大多数 Compose 控件都具有用于此目的的 interactionSource
参数。使用方法如下:
val interactionSource = remember { MutableInteractionSource() }
val pressed by interactionSource.collectIsPressedAsState()
Button(
onClick = {},
interactionSource = interactionSource,
) {
}