I have HorizontalPager with Images inside of swipeable card. Here's how it looks
And you can swipe those cards like this.
The issue is when I'm pressing down on horizontal pager it intercepts all drag gestures, I want to be able to swipe it on overscroll. If I'm on the first image - swipe to the left should be enabled, and if I'm on the last one -> swipe to the right.
Here is the code of horizontal pager with swipe modifier:
Card(
modifier = modifier
.swipableCard(
state = swipeState,
onSwiped = {
when (it) {
Direction.Left -> onLeftSwipe()
Direction.Right -> onRightSwipe()
else -> {}
}
},
blockedDirections = listOf(Direction.Up, Direction.Down)
),
colors = CardDefaults.elevatedCardColors(containerColor = MaterialTheme.colors.surface),
shape = RoundedCornerShape(16.dp)
) {
Box(modifier = Modifier.fillMaxSize()) {
PostCardInfoUi(
post = post,
onDescriptionClicked = onDescriptionClicked,
onOwnProfileClicked = onOwnProfileClicked,
onOtherProfileClicked = onOtherProfileClicked,
pagerState = pagerState
)
ReactionOverlay(
modifier = Modifier.fillMaxSize(),
isLike = swipeState.offset.value.x > 0,
alpha = (absoluteOffsetDp.value / 100).coerceAtLeast(0f)
)
}
}
And here is swipe modifier itself with all related code
fun Modifier.swipableCard(
state: SwipeableCardState,
onSwiped: (Direction) -> Unit,
onSwipeCancel: () -> Unit = {},
blockedDirections: List<Direction> = listOf(Direction.Up, Direction.Down),
) = pointerInput(key1 = pagerPage, key2 = pagerCoordsRect) {
coroutineScope {
detectDragGestures(
onDragCancel = {
launch {
state.reset()
onSwipeCancel()
}
},
onDrag = { change, dragAmount ->
launch {
Log.i("SwipableCard", "Drag amount: $dragAmount")
val original = state.offset.targetValue
val summed = original + dragAmount
val newValue = Offset(
x = summed.x.coerceIn(-state.maxWidth, state.maxWidth),
y = summed.y.coerceIn(-state.maxHeight, state.maxHeight)
)
if (change.positionChange() != Offset.Zero) change.consume()
state.drag(newValue.x, newValue.y)
}
},
onDragEnd = {
launch {
val coercedOffset = state.offset.targetValue
.coerceIn(
blockedDirections,
maxHeight = state.maxHeight,
maxWidth = state.maxWidth
)
if (hasNotTravelledEnough(state, coercedOffset)) {
state.reset()
onSwipeCancel()
} else {
val horizontalTravel = abs(state.offset.targetValue.x)
val verticalTravel = abs(state.offset.targetValue.y)
if (horizontalTravel > verticalTravel) {
if (state.offset.targetValue.x > 0) {
state.swipe(Direction.Right)
onSwiped(Direction.Right)
} else {
state.swipe(Direction.Left)
onSwiped(Direction.Left)
}
} else {
if (state.offset.targetValue.y < 0) {
state.swipe(Direction.Up)
onSwiped(Direction.Up)
} else {
state.swipe(Direction.Down)
onSwiped(Direction.Down)
}
}
}
}
},
)
}
}.graphicsLayer {
translationX = state.offset.value.x
translationY = state.offset.value.y
rotationZ = (state.offset.value.x / 60).coerceIn(-40f, 40f)
}
private fun Offset.coerceIn(
blockedDirections: List<Direction>,
maxHeight: Float,
maxWidth: Float,
): Offset {
return copy(
x = x.coerceIn(
if (blockedDirections.contains(Direction.Left)) {
0f
} else {
-maxWidth
},
if (blockedDirections.contains(Direction.Right)) {
0f
} else {
maxWidth
}
),
y = y.coerceIn(
if (blockedDirections.contains(Direction.Up)) {
0f
} else {
-maxHeight
},
if (blockedDirections.contains(Direction.Down)) {
0f
} else {
maxHeight
}
)
)
}
private fun hasNotTravelledEnough(
state: SwipeableCardState,
offset: Offset,
): Boolean {
return abs(offset.x) < state.maxWidth / 4 &&
abs(offset.y) < state.maxHeight / 4
}
enum class Direction {
Left, Right, Up, Down
}
@Composable
fun rememberSwipeableCardState(): SwipeableCardState {
val screenWidth = with(LocalDensity.current) {
LocalConfiguration.current.screenWidthDp.dp.toPx()
}
val screenHeight = with(LocalDensity.current) {
LocalConfiguration.current.screenHeightDp.dp.toPx()
}
return remember {
SwipeableCardState(screenWidth, screenHeight)
}
}
class SwipeableCardState(
internal val maxWidth: Float,
internal val maxHeight: Float,
) {
val offset = Animatable(offset(0f, 0f), Offset.VectorConverter)
/**
* The [Direction] the card was swiped at.
*
* Null value means the card has not been swiped fully yet.
*/
var swipedDirection: Direction? by mutableStateOf(null)
private set
internal suspend fun reset() {
offset.animateTo(offset(0f, 0f), tween(400))
}
suspend fun swipe(direction: Direction, animationSpec: AnimationSpec<Offset> = tween(400)) {
val endX = maxWidth * 1.5f
val endY = maxHeight
when (direction) {
Direction.Left -> offset.animateTo(offset(x = -endX), animationSpec)
Direction.Right -> offset.animateTo(offset(x = endX), animationSpec)
Direction.Up -> offset.animateTo(offset(y = -endY), animationSpec)
Direction.Down -> offset.animateTo(offset(y = endY), animationSpec)
}
this.swipedDirection = direction
}
private fun offset(x: Float = offset.value.x, y: Float = offset.value.y): Offset {
return Offset(x, y)
}
internal suspend fun drag(x: Float, y: Float) {
offset.animateTo(offset(x, y))
}
}
What I've tried: I've tried to write my own detectDragGestures extension function and passed HorizontalPager coordinates to it with current page state(first, middle, last), but couldn't make it, If I consume awaitFirstDown() pointer input, pager doesn't get it and doesn't move, If I wait for touchSlop to pass to decide what to do (swipe pager or swipe card) based on positionChange() direction and position coordinates, horizontal pager consumes awaitFirstDown() pointer and drag of the card doesn't happen.
-
If I consume awaitFirstDown() pointer input, pager doesn't get it and doesn't move
Drag and scroll check awaitFirstDown
with requireUnconsumed
false and because of that the statement above is not true, you can't prevent drag or scroll commencing by consuming awaitFirstDown
event. Consuming awaitPointerEvent
stops scroll or drag, and by doing so you can stop HorizontalPager scrolling but in your case it's not even required to stop scrolling because you look for overscroll on first page and last page.
internal suspend fun PointerInputScope.detectDragGestures(
onDragStart:
(
down: PointerInputChange, slopTriggerChange: PointerInputChange, overSlopOffset: Offset
) -> Unit,
onDragEnd: (change: PointerInputChange) -> Unit,
onDragCancel: () -> Unit,
shouldAwaitTouchSlop: () -> Boolean,
orientationLock: Orientation?,
onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit
) {
var overSlop: Offset
awaitEachGesture {
val initialDown = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
val awaitTouchSlop = shouldAwaitTouchSlop()
if (!awaitTouchSlop) {
initialDown.consume()
}
val down = awaitFirstDown(requireUnconsumed = false)
var drag: PointerInputChange?
overSlop = Offset.Zero
if (awaitTouchSlop) {
do {
drag =
awaitPointerSlopOrCancellation(
down.id,
down.type,
orientation = orientationLock
) { change, over ->
change.consume()
overSlop = over
}
} while (drag != null && !drag.isConsumed)
} else {
drag = initialDown
}
if (drag != null) {
onDragStart.invoke(down, drag, overSlop)
onDrag(drag, overSlop)
val upEvent =
drag(
pointerId = drag.id,
onDrag = {
onDrag(it, it.positionChange())
it.consume()
},
orientation = orientationLock,
motionConsumed = { it.isConsumed }
)
if (upEvent == null) {
onDragCancel()
} else {
onDragEnd(upEvent)
}
}
}
}
awaitPointerSlopOrCancellation checks consumed first then in Final pass this is where you can't pass since scroll consumes it, the part dragEvent.isConsumed
it happens
private suspend inline fun AwaitPointerEventScope.awaitPointerSlopOrCancellation(
pointerId: PointerId,
pointerType: PointerType,
orientation: Orientation?,
onPointerSlopReached: (PointerInputChange, Offset) -> Unit,
): PointerInputChange? {
if (currentEvent.isPointerUp(pointerId)) {
return null // The pointer has already been lifted, so the gesture is canceled
}
val touchSlop = viewConfiguration.pointerSlop(pointerType)
var pointer: PointerId = pointerId
val touchSlopDetector = TouchSlopDetector(orientation)
while (true) {
val event = awaitPointerEvent()
val dragEvent = event.changes.fastFirstOrNull { it.id == pointer } ?: return null
if (dragEvent.isConsumed) {
return null
} else if (dragEvent.changedToUpIgnoreConsumed()) {
val otherDown = event.changes.fastFirstOrNull { it.pressed }
if (otherDown == null) {
// This is the last "up"
return null
} else {
pointer = otherDown.id
}
} else {
val postSlopOffset = touchSlopDetector.addPointerInputChange(dragEvent, touchSlop)
if (postSlopOffset.isSpecified) {
onPointerSlopReached(dragEvent, postSlopOffset)
if (dragEvent.isConsumed) {
return dragEvent
} else {
touchSlopDetector.reset()
}
} else {
// verify that nothing else consumed the drag event
awaitPointerEvent(PointerEventPass.Final)
if (dragEvent.isConsumed) {
return null
}
}
}
}
}
If checking for slop or threshold is not an issue you can write a down, move and up gesture as mentioned in this answer. The difference between checking awaitTouchSlopOrCancellation
and drag
in original source code of detectDragGestures check if they are consumed but you don't have to and that you can get events. Also, unlike detectDragGestures which already calls consume()
in onDrag
you can conditionally call it as well.
By the way, calling change.consume()
in onDrag
has no effect because drag already calls it.
private fun Modifier.customTouch(
pass: PointerEventPass = PointerEventPass.Main,
onDown: (pointer: PointerInputChange) -> Unit,
onMove: (changes: List<PointerInputChange>) -> Unit,
onUp: () -> Unit,
) = this.then(
Modifier.pointerInput(pass) {
awaitEachGesture {
val down = awaitFirstDown(pass = pass)
onDown(down)
do {
val event: PointerEvent = awaitPointerEvent(
pass = pass
)
onMove(event.changes)
} while (event.changes.any { it.pressed })
onUp()
}
}
)
And check how consuming down or move changes HorizontalPager scroll status with
@Preview
@Composable
fun PagerConsumeTest() {
Column(
modifier = Modifier.fillMaxSize()
) {
val pagerState = rememberPagerState { 5 }
var text by remember {
mutableStateOf("")
}
var consumeDown by remember {
mutableStateOf(false)
}
var consumeMove by remember {
mutableStateOf(false)
}
Text(text, fontSize = 20.sp, modifier = Modifier.height(90.dp))
CheckBoxWithTextRippleFullRow(
label = "consumeDown",
state = consumeDown,
onStateChange = {
consumeDown = it
}
)
CheckBoxWithTextRippleFullRow(
label = "consumeMove",
state = consumeMove,
onStateChange = {
consumeMove = it
}
)
HorizontalPager(
modifier = Modifier
.border(2.dp, Color.Red)
.customTouch(
onDown = { pointer ->
text = " onDown() id: ${pointer.id}\n" +
"consumed: ${pointer.isConsumed}\n" +
"position: ${pointer.position}\n"
if (consumeDown) {
pointer.consume()
}
},
onMove = { changes ->
changes.firstOrNull()?.let {
text = " onMove() id: ${it.id}\n" +
"consumed: ${it.isConsumed}\n" +
"position: ${it.position}\n"
}
if (consumeMove) {
changes.forEach { it.consume() }
}
},
onUp = {
text = "top onUp()"
}
),
state = pagerState
) { page ->
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center) {
Text("Page: $page", fontSize = 36.sp)
}
}
}
}
By using this gesture you can drag or move, prevent scroll and with pass you can change if it receives events first and apply your logic successfully.
If you want to implement your custom drag you can modify with
1- A flag to requireUnconsumed for awaitPointerEvent
2- A flag whether you want slop control or not, in pagers, it can scroll till slop threshold is passed
3- And a PointerEventPass to change propagation direction
I built custom drag that takes these parameters, and also planning to add it to gesture library when i'm available.
And made some samples with it including one below for removing Composable on swipe from left to right on first page only.
And with params set as
detectDragGesture(
requireUnconsumed = true,
shouldAwaitTouchSlop = true,
pass = PointerEventPass.Initial,
it get events before or check it requires event to be not consumed or doesn't have to wait for slope pass if not needed