当按钮发现点击事件时,它会将其标记为已使用,这会阻止其他视图接收它。这是通过 完成的consumeDownChange()
,您可以在此处detectTapAndPress
查看完成此操作的方法Button
要覆盖默认行为,您必须重新实现一些手势跟踪。与系统相比的更改列表detectTapAndPress
:
- 我使用
awaitFirstDown(requireUnconsumed = false)
而不是默认值requireUnconsumed = true
来确保我们得到甚至消耗
- 我使用我自己的
waitForUpOrCancellationInitial
代替waitForUpOrCancellation
: 在这里我使用awaitPointerEvent(PointerEventPass.Initial)
代替awaitPointerEvent(PointerEventPass.Main)
, 以获取事件,即使其他视图会获取它。
- 移除
up.consumeDownChange()
以允许按钮处理触摸。
最终代码:
suspend fun PointerInputScope.detectTapAndPressUnconsumed(
onPress: suspend PressGestureScope.(Offset) -> Unit = NoPressGesture,
onTap: ((Offset) -> Unit)? = null
) {
val pressScope = PressGestureScopeImpl(this)
forEachGesture {
coroutineScope {
pressScope.reset()
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false).also { it.consumeDownChange() }
if (onPress !== NoPressGesture) {
launch { pressScope.onPress(down.position) }
}
val up = waitForUpOrCancellationInitial()
if (up == null) {
pressScope.cancel() // tap-up was canceled
} else {
pressScope.release()
onTap?.invoke(up.position)
}
}
}
}
}
suspend fun AwaitPointerEventScope.waitForUpOrCancellationInitial(): PointerInputChange? {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
return event.changes[0]
}
if (event.changes.fastAny { it.consumed.downChange || it.isOutOfBounds(size) }) {
return null // Canceled
}
// Check for cancel by position consumption. We can look on the Final pass of the
// existing pointer event because it comes after the Main pass we checked above.
val consumeCheck = awaitPointerEvent(PointerEventPass.Final)
if (consumeCheck.changes.fastAny { it.positionChangeConsumed() }) {
return null
}
}
}
PS 您需要将implementation("androidx.compose.ui:ui-util:$compose_version")
Android Compose 或implementation(compose("org.jetbrains.compose.ui:ui-util"))
Desktop Compose 添加到您build.gradle.kts
的使用fastAll
/fastAny
中。
用法:
Card(
modifier = Modifier
.width(150.dp).height(64.dp)
.clickable { }
.pointerInput(Unit) {
detectTapAndPressUnconsumed(onTap = {
println("tap")
})
}
) {
Column {
Button({ println("Clicked button") }) { Text("Click me") }
}
}