drag

Function

Common
suspend fun AwaitPointerEventScope.drag(
    pointerId: PointerId,
    onDrag: (PointerInputChange) -> Unit,
): Boolean

Reads position change events for pointerId and calls onDrag for every change in position. If pointerId is raised, a new pointer is chosen from those that are down and if none exist, the method returns. This does not wait for touch slop.

Example Usage:

Returns

true if the drag completed normally or false if the drag motion was canceled by another gesture detector consuming position change events.

Code Examples

DragSample

@Composable
fun DragSample() {
    val offsetX = remember { mutableStateOf(0f) }
    val offsetY = remember { mutableStateOf(0f) }
    var size by remember { mutableStateOf(Size.Zero) }
    Box(Modifier.fillMaxSize().onSizeChanged { size = it.toSize() }) {
        Box(
            Modifier.offset { IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt()) }
                .size(50.dp)
                .background(Color.Blue)
                .pointerInput(Unit) {
                    awaitEachGesture {
                        val down = awaitFirstDown()
                        val change =
                            awaitTouchSlopOrCancellation(down.id) { change, over ->
                                val original = Offset(offsetX.value, offsetY.value)
                                val summed = original + over
                                val newValue =
                                    Offset(
                                        x = summed.x.coerceIn(0f, size.width - 50.dp.toPx()),
                                        y = summed.y.coerceIn(0f, size.height - 50.dp.toPx()),
                                    )
                                change.consume()
                                offsetX.value = newValue.x
                                offsetY.value = newValue.y
                            }
                        if (change != null) {
                            drag(change.id) {
                                val original = Offset(offsetX.value, offsetY.value)
                                val summed = original + it.positionChange()
                                val newValue =
                                    Offset(
                                        x = summed.x.coerceIn(0f, size.width - 50.dp.toPx()),
                                        y = summed.y.coerceIn(0f, size.height - 50.dp.toPx()),
                                    )
                                it.consume()
                                offsetX.value = newValue.x
                                offsetY.value = newValue.y
                            }
                        }
                    }
                }
        )
    }
}