如何使用 Jetpack Compose 按钮​​后面的视图检测点击?

How can I detect a click with the view behind a Jetpack Compose Button?

以下代码适用于 Jetbrains Desktop Compose。它显示一张带有按钮的卡片,现在如果您单击该卡片,“clicked card”将回显到控制台。如果您单击该按钮,它将回显“已单击按钮”

但是,我正在寻找一种方法让卡片检测按钮上的点击。我想在不更改按钮的情况下执行此操作,因此按钮不需要知道它所在的卡。我希望这样做,以便卡片知道它表面上的某些东西已被处理,例如显示不同颜色的边框..

期望的结果是,当您单击按钮时,日志将同时显示“Card clicked”和“Button clicked”行。我明白为什么不调用 mouseClickable,按钮声明已处理点击。所以我希望我需要使用除 mouseClickable 之外的另一种鼠标方法。但我一辈子都想不出我应该用什么。

@OptIn(ExperimentalComposeUiApi::class, androidx.compose.foundation.ExperimentalDesktopApi::class)
@Composable
fun example() {
    Card(
        modifier = Modifier
            .width(150.dp).height(64.dp)
            .mouseClickable { println("Clicked card") }
    ) {
        Column {
            Button({ println("Clicked button")}) { Text("Click me") }
        }
    }
}

当按钮发现点击事件时,它会将其标记为已消耗,从而防止其他视图接收到它。这是用 consumeDownChange() 完成的,你可以看到 detectTapAndPress 方法,其中这是用 Button here

完成的

要覆盖默认行为,您必须重新实现一些手势跟踪。与系统相比的更改列表 detectTapAndPress:

  1. 我使用 awaitFirstDown(requireUnconsumed = false) 而不是默认的 requireUnconsumed = true 来确保我们得到均匀的消耗
  2. 我使用我自己的 waitForUpOrCancellationInitial 而不是 waitForUpOrCancellation:这里我使用 awaitPointerEvent(PointerEventPass.Initial) 而不是 awaitPointerEvent(PointerEventPass.Main),以便即使其他视图会获取事件明白了。
  3. 删除 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
        }
    }
}

P.S。您需要将 implementation("androidx.compose.ui:ui-util:$compose_version") for Android Compose 或 implementation(compose("org.jetbrains.compose.ui:ui-util")) for 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") }
    }
}