DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Gesture Detection in Jetpack Compose -Tap, Drag, Pinch & Swipe

Handle user interactions with Compose gesture detectors!

detectTapGestures

Handle tap, double-tap, and long-press:

Box(
    modifier = Modifier
        .size(200.dp)
        .background(Color.Blue)
        .pointerInput(Unit) {
            detectTapGestures(
                onTap = { offset ->
                    println("Single tap at ${'$'}offset")
                },
                onDoubleTap = { offset ->
                    println("Double tap at ${'$'}offset")
                },
                onLongPress = { offset ->
                    println("Long press at ${'$'}offset")
                }
            )
        }
)
Enter fullscreen mode Exit fullscreen mode

detectDragGestures

Track dragging motion:

var offsetX by remember { mutableFloatStateOf(0f) }
var offsetY by remember { mutableFloatStateOf(0f) }

Box(
    modifier = Modifier
        .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
        .size(100.dp)
        .background(Color.Red)
        .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
                offsetX += dragAmount.x
                offsetY += dragAmount.y
            }
        }
)
Enter fullscreen mode Exit fullscreen mode

detectTransformGestures for Pinch Zoom

Handle multi-touch pinch zoom:

var scale by remember { mutableFloatStateOf(1f) }

Box(
    modifier = Modifier
        .size(200.dp)
        .scale(scale)
        .background(Color.Green)
        .pointerInput(Unit) {
            detectTransformGestures { _, pan, zoom, rotation ->
                scale *= zoom
            }
        }
)
Enter fullscreen mode Exit fullscreen mode

Swipe Direction Detection

Detect swipe gestures in specific directions:

Box(
    modifier = Modifier
        .size(200.dp)
        .background(Color.Yellow)
        .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
                when {
                    dragAmount.x > 50 -> println("Swipe right")
                    dragAmount.x < -50 -> println("Swipe left")
                    dragAmount.y > 50 -> println("Swipe down")
                    dragAmount.y < -50 -> println("Swipe up")
                }
            }
        }
)
Enter fullscreen mode Exit fullscreen mode

Create responsive, touch-friendly interfaces with gesture detection!


8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)