-
-
Save Ahmed-Sellami/3a270b9fde77d5550ec9ad62c53e098b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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