DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Gesture Detection in Compose: Tap, Drag, Swipe, and Multitouch

Jetpack Compose provides powerful gesture detection APIs for building interactive, responsive UIs.

Detecting Taps

@Composable
fun TapDetection() {
    var tapCount by remember { mutableStateOf(0) }

    Box(
        modifier = Modifier
            .size(200.dp)
            .background(Color.LightGray)
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = { offset ->
                        tapCount++
                    },
                    onDoubleTap = { offset ->
                        tapCount = 0
                    }
                )
            },
        contentAlignment = Alignment.Center
    ) {
        Text("Taps: $tapCount")
    }
}
Enter fullscreen mode Exit fullscreen mode

Drag and Pan Gestures

@Composable
fun DragGesture() {
    var offset by remember { mutableStateOf(Offset.Zero) }

    Box(
        modifier = Modifier
            .size(300.dp)
            .background(Color.LightGray)
            .pointerInput(Unit) {
                detectDragGestures(
                    onDrag = { change, dragAmount ->
                        offset += dragAmount
                    }
                )
            }
    ) {
        Box(
            modifier = Modifier
                .size(50.dp)
                .background(Color.Red)
                .offset(offset.x.dp, offset.y.dp)
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

Swipe Detection

@Composable
fun SwipeDetection() {
    var swipeDirection by remember { mutableStateOf("") }

    Box(
        modifier = Modifier
            .size(200.dp)
            .background(Color.LightGray)
            .pointerInput(Unit) {
                detectHorizontalDragGestures { change, dragAmount ->
                    swipeDirection = if (dragAmount > 0) "Right" else "Left"
                }
            },
        contentAlignment = Alignment.Center
    ) {
        Text("Swipe: $swipeDirection")
    }
}
Enter fullscreen mode Exit fullscreen mode

Multitouch Handling

@Composable
fun MultitouchDetection() {
    var touchCount by remember { mutableStateOf(0) }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                awaitEachGesture {
                    val event = awaitPointerEvent()
                    touchCount = event.changes.size
                }
            },
        contentAlignment = Alignment.Center
    ) {
        Text("Fingers: $touchCount")
    }
}
Enter fullscreen mode Exit fullscreen mode

Gesture detection creates intuitive, modern interactions in your app.


8 Android app templates available on Gumroad

Top comments (0)