I'm trying to detect swipe direction in Compose. I'm using the draggable modifier for this. But draggable allows only one direction to detect (Vertical or Horizontal). I want to detect swipes for all directions (left, right, up, down). Can anyone help me how can I do this? Thanks!
Modifier.dragGestureFilter
detects dragging in any direction. Pass an instance of DragObserver
and override onDrag
. Here you can detect the swipe direction based on the Offset
. This object has x
and y
values, which are positive or negative based on the direction.
Here's what your code could look like:
Box(
Modifier.dragGestureFilter(
dragObserver = object : DragObserver() {
override fun onDrag(dragDistance: Offset): Offset {
val (x, y) = dragDistance
when {
x > 0 -> { /* right */ }
x < 0 -> { /* left */ }
}
when {
y > 0 -> { /* down */ }
y < 0 -> { /* up */ }
}
}
}
)
)
To actually move the object, you would have to apply Modifier.offset
with values that are updated in onDrag
.