awaitHorizontalTouchSlopOrCancellation
Function
Common
suspend fun AwaitPointerEventScope.awaitHorizontalTouchSlopOrCancellation(
pointerId: PointerId,
onTouchSlopReached: (change: PointerInputChange, overSlop: Float) -> Unit,
) =
awaitPointerSlopOrCancellation(
pointerId = pointerId,
pointerType = PointerType.Touch,
onPointerSlopReached = { change, overSlop -> onTouchSlopReached(change, overSlop.x) },
orientation = Orientation.Horizontal,
)
Waits for horizontal drag motion to pass touch slop, using
pointerId as the pointer to examine. If pointerId is raised, another pointer from those that
are down will be chosen to lead the gesture, and if none are down, null is returned.
onTouchSlopReached is called after ViewConfiguration.touchSlop motion in the horizontal
direction with the change that caused the motion beyond touch slop and the pixels beyond touch
slop. onTouchSlopReached should consume the position change if it accepts the motion. If it
does, then the method returns that PointerInputChange. If not, touch slop detection will
continue. If pointerId is not down when awaitHorizontalTouchSlopOrCancellation is called,
then null is returned.
Example Usage:
Returns
The PointerInputChange that was consumed in onTouchSlopReached or null if all pointers are raised before touch slop is detected or another gesture consumed the position change. |
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
}
}
}
}
)
}
}
