Skip to content

Instantly share code, notes, and snippets.

@Ahmed-Sellami
Last active September 27, 2021 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ahmed-Sellami/3a270b9fde77d5550ec9ad62c53e098b to your computer and use it in GitHub Desktop.
Save Ahmed-Sellami/3a270b9fde77d5550ec9ad62c53e098b to your computer and use it in GitHub Desktop.
fun Modifier.dragToReorder(
onDrag: () -> Unit,
onStopDrag: () -> Unit,
): Modifier = composed {
val offsetX = remember { Animatable(0f) }
val offsetY = remember { Animatable(0f) }
pointerInput(Unit) {
// Wrap in a coroutine scope to use suspend functions for touch events and animation.
coroutineScope {
while (true) {
// Wait for a touch down event.
val pointerId = awaitPointerEventScope { awaitFirstDown().id }
// Interrupt any ongoing animation of other items.
offsetX.stop()
offsetY.stop()
// Wait for drag events.
awaitPointerEventScope {
drag(pointerId) { change ->
onDrag()
val horizontalDragOffset = offsetX.value + change.positionChange().x
launch {
offsetX.snapTo(horizontalDragOffset)
}
val verticalDragOffset = offsetY.value + change.positionChange().y
launch {
offsetY.snapTo(verticalDragOffset)
}
// Consume the gesture event, not passed to external
change.consumePositionChange()
}
}
launch {
offsetX.animateTo(0f)
}
launch {
offsetY.animateTo(0f)
onStopDrag()
}
}
}
}
.offset {
// Use the animating offset value here.
IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment