awaitHorizontalDragOrCancellation

Function

Common
suspend fun AwaitPointerEventScope.awaitHorizontalDragOrCancellation(
    pointerId: PointerId
): PointerInputChange?

Reads pointer input events until a horizontal drag is detected or all pointers are up. When the final pointer is raised, the up event is returned. When a drag event is detected, the drag change will be returned. Note that if pointerId has been raised, another pointer that is down will be used, if available, so the returned PointerInputChange.id may differ from pointerId. If the position change has been consumed by the PointerEventPass.Main pass, then the drag is considered canceled and null is returned. If pointerId is not down when awaitHorizontalDragOrCancellation is called, then null is returned.

Example Usage:

Code Examples

AwaitHorizontalDragOrCancellationSample

@Composable
fun AwaitHorizontalDragOrCancellationSample() {
    val offsetX = remember { mutableStateOf(0f) }
    val offsetY = remember { mutableStateOf(0f) }
    var width by remember { mutableStateOf(0f) }
    Box(Modifier.fillMaxSize().onSizeChanged { width = it.width.toFloat() }) {
        Box(
            Modifier.offset { IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt()) }
                .fillMaxHeight()
                .width(50.dp)
                .background(Color.Blue)
                .pointerInput(Unit) {
                    awaitEachGesture {
                        val down = awaitFirstDown()
                        var change =
                            awaitHorizontalTouchSlopOrCancellation(down.id) { change, over ->
                                val originalX = offsetX.value
                                val newValue = (originalX + over).coerceIn(0f, width - 50.dp.toPx())
                                change.consume()
                                offsetX.value = newValue
                            }
                        while (change != null && change.pressed) {
                            change = awaitHorizontalDragOrCancellation(change.id)
                            if (change != null && change.pressed) {
                                val originalX = offsetX.value
                                val newValue =
                                    (originalX + change.positionChange().x).coerceIn(
                                        0f,
                                        width - 50.dp.toPx(),
                                    )
                                change.consume()
                                offsetX.value = newValue
                            }
                        }
                    }
                }
        )
    }
}