horizontalDrag
Function
Common
suspend fun AwaitPointerEventScope.horizontalDrag(
pointerId: PointerId,
onDrag: (PointerInputChange) -> Unit,
): Boolean
Reads horizontal 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:
Code Examples
HorizontalDragSample
@Composable
fun HorizontalDragSample() {
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()
val 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
}
if (change != null) {
horizontalDrag(change.id) {
val originalX = offsetX.value
val newValue =
(originalX + it.positionChange().x).coerceIn(
0f,
width - 50.dp.toPx(),
)
it.consume()
offsetX.value = newValue
}
}
}
}
)
}
}