👆 手势基础

Compose 手势处理概述 PointerInputScope Modifier.pointerInput

🖐️ 手势哲学

Compose 将触摸、拖拽、缩放、旋转等统一为 手势修饰符,通过 PointerInputScope 协程管道处理原始指针事件,告别传统回调。

🎯 PointerInputScope

一个协程作用域,提供 awaitPointerEvent、detectTapGestures、detectDragGestures 等挂起函数,让你顺序式监听触摸流。

🧩 Modifier.pointerInput

将手势逻辑附加到 Composable 的关键修饰符。接收 key 和挂起函数块,当 key 变化时重启协程,生命周期安全。

概念说明典型用法
PointerInputScope 协程作用域,内部可调用 awaitPointerEventScope 等挂起函数,每个手势阶段(Down/Move/Up)都可被挂起等待。 awaitPointerEventScope { … }
Modifier.pointerInput 附加到 Composable 的修饰符,接受一个 key 和挂起 lambda。key 变化时取消旧协程,启动新协程。 Modifier.pointerInput(key) { … }
手势检测器 基于 PointerInputScope 封装的高级 API:
• detectTapGestures
• detectDragGestures
• detectTransformGestures
detectTapGestures(onTap = { })
@Composable
fun GestureBox() {
Box(

modifier = Modifier
.size(200.dp)
.background(Color.Cyan.copy(alpha = 0.2f))
.pointerInput(Unit) { // key = Unit 稳定
// 👇 进入 PointerInputScope
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
// 处理 PointerEvent
when (event.type) {
PointerEventType.Press -> { /* 按下 */ }
PointerEventType.Move -> { /* 移动 */ }
PointerEventType.Release -> { /* 抬起 */ }
}
}
}
}
)
}
@Composable Box / Text / Image Modifier .pointerInput(key) 协程 + 挂起 lambda PointerInput Scope awaitPointerEvent 📌 事件流:Press → Move → Release ( 可组合 detectTapGestures / detectDragGestures ) 协程安全 · 自动取消 · 与 Composable 生命周期绑定
⭐ 手势处理架构:Composable → Modifier.pointerInput → PointerInputScope 协程管道
// 使用高级手势检测器 (基于 PointerInputScope)
Modifier.pointerInput(Unit) {
detectTapGestures(
onTap = { offset -> /* 点击 */ },
onDoubleTap = { offset -> /* 双击 */ },
onLongPress = { offset -> /* 长按 */ }
)
}