Tom Taila
Tom Taila

Reputation: 581

What is the "View.onTouchListener" equivalent in Jetpack Compose? I need the touch coordinates

This is what we would currently use in typical Views: https://developer.android.com/reference/android/view/View.OnTouchListener

Is there an equivalent in Jetpack Compose?

Upvotes: 10

Views: 8101

Answers (3)

Blundell
Blundell

Reputation: 76534

https://stackoverflow.com/a/66807594/413127 is the correct answer.

In addition. to detect tap & drag at the same time, you need to use two pointerInput modifiers.

modifier
.pointerInput(Unit) {
    detectTapGestures { offset ->
        // on tap    
    }
}
.pointerInput(Unit) {
    detectDragGestures { change, dragAmount ->
        // on drag
    }
}

Upvotes: 0

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364730

With 1.0.0 you can use the PointerInput mod

For example you can use detectTapGestures:

Modifier.pointerInput(Unit) {
    detectTapGestures(
        onPress = {/* Called when the gesture starts */ },
        onDoubleTap = { /* Called on Double Tap */ },
        onLongPress = { /* Called on Long Press */ },
        onTap = { /* Called on Tap */ }
    )
}

or the detectDragGestures:

Box(
    Modifier
        .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
                change.consumeAllChanges()
                //...
            }
        }
)

You can also use some modifiers like: .scrollable, .clickable, .draggable, .swipeable.

Upvotes: 19

nglauber
nglauber

Reputation: 23994

In compose beta-05 version, you can use:

Text("Your Composable", modifier = Modifier.pointerInput(Unit) {
    detectTransformGestures { centroid, pan, zoom, rotation ->
    }
    // or
    detectDragGestures { change, dragAmount ->  }
    // or
    detectTapGestures(
        onPress = { offset ->  },
        onDoubleTap = { offset -> },
        onLongPress = { offset -> },
        onTap = { offset ->  }
    )
    // or other similar...
})

Upvotes: 4

Related Questions