Jetpack Compose Gesture — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Gesture. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Taps register on the wrong element, drag gestures fight with scroll, or multi-touch pinches are ignored entirely.
Wrong Approach ❌
@Composable
fun BadGesture() {
var offset by remember { mutableStateOf(Offset.Zero) }
Box(
modifier = Modifier
.size(100.dp)
.pointerInput(Unit) {
// Coordinates from PointerInputScope — wrong coordinate space
awaitPointerEventScope {
val event = awaitPointerEvent()
offset = event.changes.first().position
}
}
)
}
@Composable
fun TapOnScroll() {
LazyColumn {
item {
Box(modifier = Modifier.clickable { /* Never triggers */ })
}
}
}
Output: Wrong offset values. Scroll intercepts tap events.
Right Approach ✅
@Composable
fun GoodGesture() {
var offset by remember { mutableStateOf(Offset.Zero) }
Box(
modifier = Modifier
.size(100.dp)
.pointerInput(Unit) {
detectTapGestures(
onTap = { offset = it },
onDoubleTap = { /* reset */ },
onLongPress = { /* menu */ }
)
}
)
}
// Drag gesture
@Composable
fun DragBox() {
var offsetX by remember { mutableStateOf(0f) }
Box(
modifier = Modifier
.offset { IntOffset(offsetX.roundToInt(), 0) }
.pointerInput(Unit) {
detectHorizontalDragGestures { _, dragAmount ->
offsetX += dragAmount
}
}
.size(100.dp)
)
}
Output: Correct gesture detection with proper coordinate handling.
Prevention
- Use
detectTapGestures,detectDragGestures, etc. — don't handle raw events. - Use
Modifier.clickableoverdetectTapGestureswhen no custom logic is needed. - Add
.then(Modifier.scrollable(...))before gesture modifiers to avoid conflicts. - Use
detectTransformGesturesfor pinch-zoom and rotation.
Common Mistakes with compose gesture
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro