Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 104 ยท Building a Real UI

Gestures and Input Events in Compose

Handle taps, long presses, drags, swipes, pinch-zoom, scrolling and keyboard focus in Jetpack Compose with clickable, pointerInput, draggable, transformable and nested scroll.

Touch is how people use phones, so a screen is only as good as its reaction to fingers: a tap that opens, a long press that selects, a drag that reorders, a swipe that dismisses, a pinch that zooms. Compose gives you a ladder of tools. At the bottom are one-line modifiers for common cases. In the middle are modifiers for a single kind of gesture. At the top is pointerInput, which lets you read raw touch events and build any gesture you like.

The rule of thumb is to use the highest-level tool that does the job, because the high-level ones also handle accessibility, ripples, focus and keyboard activation for you. This lesson climbs the ladder, then covers scrolling, nested scrolling, keyboard and focus, and a short note on the older View system. The Android UI cannot run here, so the real Compose code is read-only; the TryIts are plain Kotlin stand-ins that model a gesture recognizer and scroll dispatch, which are the ideas that matter.

Click, long click and double click

Modifier.clickable makes any composable tappable, and it adds the ripple, the focus highlight, keyboard activation (Enter) and a screen reader action for free. Give it a label for accessibility.

Kotlin
// read-only example
Text(
    text = "Mark as read",
    modifier = Modifier
        .clickable(onClickLabel = "Mark message as read") { viewModel.markRead(id) }
        .padding(16.dp),
)

Order matters in modifier chains (see modifiers): put clickable before padding if you want the padding to be part of the tap target, as above, and after clip if the ripple must follow a shape.

When one element needs several reactions, use combinedClickable (it is marked @ExperimentalFoundationApi in many versions):

Kotlin
// read-only example
@OptIn(ExperimentalFoundationApi::class)
Modifier.combinedClickable(
    onClick = { open(item) },
    onLongClick = { startSelection(item) },
    onDoubleClick = { toggleFavorite(item) },
)

A double click makes the single click wait: the system must see whether a second tap follows, so the single-click handler fires slightly late. Use a double click only for secondary shortcuts, never for the only way to do something, because it is hard to discover.

Other one-liners: toggleable (on/off with a checkbox-like role), selectable (one choice in a group) and Modifier.indication for a custom ripple. A disabled clickable still takes part in layout; use enabled = false instead of removing the modifier.

pointerInput and detectTapGestures

When you need the position of a tap, or press feedback, use pointerInput with a gesture detector. pointerInput(key) runs a suspend block that reads touch events; the key restarts the block when it changes (see side effects for why keys matter).

Kotlin
// read-only example: tap anywhere to drop a marker, long press to clear
var markers by remember { mutableStateOf(listOf<Offset>()) }

Box(
    Modifier
        .fillMaxSize()
        .pointerInput(Unit) {
            detectTapGestures(
                onTap = { position -> markers = markers + position },
                onLongPress = { markers = emptyList() },
                onDoubleTap = { position -> /* zoom to position */ },
                onPress = { /* a finger went down; awaitRelease() waits for lift */ },
            )
        }
) {
    markers.forEach { Marker(it) }
}

Note: plain pointerInput does not add accessibility actions. If a tap through pointerInput is the only way to trigger something, TalkBack users cannot do it. Prefer clickable unless you really need positions, and add custom semantic actions (Modifier.semantics { onClick(label = "...") { true } }) when you do.

How a gesture is recognized

The system decides what a touch means by time and distance. A tap is a press and release within a short time and a small movement. A long press is a press held for about 400 ms or more without moving. A drag starts when the finger moves farther than the touch slop, a small distance (about 8 dp) that separates a shaky tap from a deliberate move. Compose exposes the slop as viewConfiguration.touchSlop.

The stand-in below is a tiny recognizer with these rules. It receives a recorded stream of events (down, move, up with time and position) and says what gesture happened. It is not Compose, but it is exactly the decision detectTapGestures and detectDragGestures make for you.

Kotlin A tiny gesture recognizer (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Dragging, swiping and anchors

For movement on one axis, use Modifier.draggable with a rememberDraggableState. It reports the delta of every move, and you decide what to do with it, usually updating an offset.

Kotlin
// read-only example: a horizontally draggable box
var offsetX by remember { mutableFloatStateOf(0f) }

Box(
    Modifier
        .offset { IntOffset(offsetX.roundToInt(), 0) }
        .size(80.dp)
        .background(Color.Blue)
        .draggable(
            orientation = Orientation.Horizontal,
            state = rememberDraggableState { delta -> offsetX += delta },
        )
)

For free movement in two dimensions use pointerInput with detectDragGestures(onDrag = { change, dragAmount -> change.consume(); offset += dragAmount }). Call change.consume() so the parent does not also treat the same movement as a scroll.

For "swipe to dismiss" and "drag to reveal", you want the element to settle at defined positions after the finger lifts, which is what AnchoredDraggable does. It is the modern replacement for the old swipeable modifier: you declare anchors (for example Closed at 0 and Open at -240.dp), and it handles velocity and snapping. Material 3 builds on it in SwipeToDismissBox, the easiest choice for list items:

Kotlin
// read-only example: swipe a list row away to delete it
val dismissState = rememberSwipeToDismissBoxState(
    confirmValueChange = { value ->
        if (value == SwipeToDismissBoxValue.EndToStart) { onDelete(item); true } else false
    },
)
SwipeToDismissBox(
    state = dismissState,
    backgroundContent = { Box(Modifier.fillMaxSize().background(Color.Red)) },
) {
    ListItem(headlineContent = { Text(item.title) })
}

Always provide a non-gesture alternative to a swipe (a delete button, a menu, or an undo snackbar), because swipe-only actions are hard to discover and unusable with some assistive technology. See scaffold and app bars for snackbars.

Pinch, rotate and transform

Modifier.transformable handles multi-touch: it gives you the zoom factor, rotation in degrees and pan offset of a gesture. You apply them with graphicsLayer.

Kotlin
// read-only example: pinch-to-zoom image
var scale by remember { mutableFloatStateOf(1f) }
var rotation by remember { mutableFloatStateOf(0f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val state = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
    scale = (scale * zoomChange).coerceIn(1f, 5f)
    rotation += rotationChange
    offset += offsetChange
}

Image(
    painter = painterResource(R.drawable.photo),
    contentDescription = "Trip photo",
    modifier = Modifier
        .graphicsLayer(scaleX = scale, scaleY = scale, rotationZ = rotation,
                       translationX = offset.x, translationY = offset.y)
        .transformable(state),
)

The key detail is coerceIn on the scale: without limits the user can pinch an image to nothing or to a huge size. For zoom around the pinch center rather than the image center, also use the centroid that detectTransformGestures provides inside pointerInput.

Scrolling and nested scroll

verticalScroll and horizontalScroll make a Column or Row scrollable; LazyColumn (see lazy lists) scrolls by itself. Modifier.scrollable is the lower-level building block: it only reports scroll deltas, and you draw the content yourself.

The tricky part is nested scrolling, where a scrollable sits inside another one, such as a list inside a collapsing toolbar. The protocol works in four steps, as events pass up and down the tree:

  1. First the parent is asked via onPreScroll. It may consume part of the delta, for example to collapse the toolbar before the list moves.
  2. The child scrolls with what is left.
  3. The parent is offered the remainder in onPostScroll.
  4. Fling velocity goes through the same chain (onPreFling, onPostFling).

Compose's built-in collapsing app bars use this protocol through TopAppBarDefaults.exitUntilCollapsedScrollBehavior() and Modifier.nestedScroll(scrollBehavior.nestedScrollConnection); see scaffold and app bars. A custom NestedScrollConnection lets you build your own.

The second stand-in simulates this with a collapsing header (height 120 down to 56) above a list. It shows how a drag is split between header and list.

Kotlin Nested scroll: header first, then list (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Keyboard, focus and other input

Phones also receive input from hardware keyboards, D-pads, game controllers and Chromebook trackpads, and TalkBack moves focus from item to item. Compose handles the basics, but you should know the tools:

  • Focus: Modifier.focusable() makes an element focusable, FocusRequester with Modifier.focusRequester(...) lets you move focus from code (for example to the first invalid field), and LocalFocusManager.current.clearFocus() dismisses the keyboard when the user taps outside a text field (see inputs and forms).
  • Key events: Modifier.onKeyEvent { ... } or onPreviewKeyEvent reacts to keys, for example Ctrl+Enter to send a message; return true if you handled it.
  • Focus order: arrow keys and Tab move focus by geometry. Override with Modifier.focusProperties { next = otherRequester }.
  • Mouse and hover: Modifier.hoverable and onPointerEvent matter on large screens and Chromebooks (see adaptive layouts).

Test gestures with the Compose test rule: performClick(), performTouchInput { swipeLeft() } and performKeyInput are covered in Compose UI testing.

The View system

In the old View system a click is view.setOnClickListener { ... }, a long press is setOnLongClickListener, and anything more complex goes through GestureDetector (with onSingleTapUp, onFling, onScroll) or ScaleGestureDetector for pinch, fed from onTouchEvent. Parents can steal events from children with onInterceptTouchEvent. A Compose ComposeView inside a View hierarchy, or an AndroidView inside Compose, follows the rules in Views interop. Concepts are identical: slop, long-press timeout, consuming events.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why prefer Modifier.clickable over detectTapGestures for an ordinary button-like element?

    Higher-level modifiers include semantics and interaction feedback. A raw pointerInput tap has none of that unless you add it.
  2. 2. What is the touch slop?

    Fingers wobble. Movement within the slop (about 8 dp) is still a tap; beyond it the gesture becomes a drag.
  3. 3. Which tool is the recommended way to build swipe-to-delete rows in Material 3?

    SwipeToDismissBox is built on AnchoredDraggable and handles velocity, snapping and background content. Always offer a non-swipe alternative too.
  4. 4. In nested scrolling, who gets the first chance to consume a scroll delta?

    The protocol is pre-scroll (parent), scroll (child), post-scroll (parent gets the remainder). This is how a toolbar collapses before the list starts to scroll.
  5. 5. What does change.consume() do in a drag handler?

    Consuming marks the event as handled, so a parent scroll container does not also react to the same drag.

Summary

  • Climb the ladder: clickable / combinedClickable, then draggable, transformable, scrollable, and pointerInput with detectTapGestures / detectDragGestures only when you need raw control.
  • Touch slop and time thresholds separate taps, long presses and drags.
  • SwipeToDismissBox and AnchoredDraggable handle anchored swipes; always offer a non-gesture alternative.
  • transformable plus graphicsLayer gives pinch, rotate and pan; clamp the scale.
  • Nested scroll runs parent pre-scroll, child scroll, then parent post-scroll.
  • Use focus, onKeyEvent and semantics so keyboard and TalkBack users are not left out.

Next: WebView and Search