What I want to achieve:
I’m attempting to make something relatively similar to Instagram stories. When the user taps on either side of the screen (left / right), it should navigate between the specific story’s data (picture, text etc.). If the user longpresses the middle of the screen, a different function should be called, f.e to pause the story progress (timer). When the user swipes to either side, it should navigate to a previous/next story. When the user swipes vertically (top -> bottom), a different screen should be opened, displaying more story-specific information.
How I wanted to achieve this:
A HorizontalPager
to switch between the stories. Using gesture detection, specifically with a custom .pointerInput
/ awaitEachGesture
implementation, I was hoping to handle the taps & vertical swipes. The horizontal swipes would be handled by the HorizontalPager
itself.
The issue which occurs:
When the pager has been used to swipe to the next entry (story), quickly tapping the sides after the drag finished and the page is settled does not seem to actually be detected by the gesture detector. Instead of the events being handled within the awaitEachGesture
, it seems to be handled by the HorizontalPager
instead, specifically as a DragInteraction.Start
, even though it’s not a dragging movement, but a simple tap.
This results in the logic for side tapping (displaying different data from the same story) not being called. If the taps are not done directly after the swipe, but after a small delay, the awaitEachGesture
implementation handles the tap correctly.
Code to reproduce the issue:
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalFoundationApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
val pagerState = rememberPagerState(pageCount = { 5 })
LaunchedEffect(Unit) {
pagerState.interactionSource.interactions.collectLatest { interaction ->
when (interaction) {
is DragInteraction.Start -> log("drag interaction start")
is DragInteraction.Stop -> log("drag interaction stop")
is DragInteraction.Cancel -> log("drag interaction cancel")
}
}
}
Scaffold {
Column(
modifier = Modifier.padding(it)
) {
HorizontalPager(
state = pagerState,
) { page ->
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown().also { pointerInputChange ->
pointerInputChange.consume()
log("first down consumed")
}
waitForUpOrCancellation()?.also { pointerInputChange ->
pointerInputChange.consume()
log("up consumed")
}
}
},
contentAlignment = Alignment.Center,
) {
Text(text = "Page index: $page")
}
}
}
}
}
}
private fun log(message: String) = Log.d(TAG, message)
private companion object {
const val TAG = "-=-"
}
}
4
If it’s the issue is not being able to receive awaitFirstDown
nor waitForUpOrCancellation
after drag starts is it happens because pager consumes awaitFirstDown or other ones and because of that you won’t able to get it unless you call awaitFirstDown with requireUnconsumed = false
which will let awaitFirstDown
to get event and following up even if any descendant or, ancestor depending on pass, Modifier consumed it.
Also, drag modifiers call awaitFirstDown with false and PointerEventPass.Initial and thanks to that drag can receive gestures even if you consume them and before any child modifier thanks to pass, which makes consuming useless against drag gestures which prints as in your case without setting requireUnconsumed = false
I Is it consumed before false
I first down consumed
I drag interaction start
I drag interaction stop
If you set requireUnconsumed = false
and tap while drag is going on it will log
I Is it consumed before false
I first down consumed
I drag interaction start
I drag interaction stop
I Is it consumed before true
I first down consumed
I drag interaction start
I up consumed
I drag interaction cancel
As you can see in result you can still get up PointerInputCgange? while pagerState.isScrollInProgress
Demo
@Preview
@Composable
fun Test() {
val pagerState = rememberPagerState(pageCount = { 5 })
LaunchedEffect(Unit) {
pagerState.interactionSource.interactions.collectLatest { interaction ->
when (interaction) {
is DragInteraction.Start -> println("drag interaction start")
is DragInteraction.Stop -> println("drag interaction stop")
is DragInteraction.Cancel -> println("drag interaction cancel")
}
}
}
var color by remember {
mutableStateOf(Color.Blue)
}
var text by remember {
mutableStateOf("Idle")
}
Column(
modifier = Modifier
) {
Text(text = text, color = color, fontSize = 14.sp, maxLines = 2)
HorizontalPager(
state = pagerState,
) { page ->
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(
requireUnconsumed = false
).also { pointerInputChange ->
println("Is it consumed before ${pointerInputChange.isConsumed}")
pointerInputChange.consume()
println("first down consumed, isScrolling: ${pagerState.isScrollInProgress}")
}
text = "Down $down, isScrolling: ${pagerState.isScrollInProgress}"
color = Color.Red
val up = waitForUpOrCancellation()
?.also { pointerInputChange ->
pointerInputChange.consume()
println("up consumed, isScrolling: ${pagerState.isScrollInProgress}")
}
text = "Up isScrolling: ${pagerState.isScrollInProgress}, $up"
color = Color.Magenta
}
},
contentAlignment = Alignment.Center,
) {
Text(text = "Page index: $page")
}
}
}
}
More detailed explanation about gestures you can check this answer.
And drag detection code of LazyLists which also happens to be Pager too, that checks first down
private fun Modifier.dragDirectionDetector(state: PagerState) =
this then Modifier.pointerInput(state) {
coroutineScope {
awaitEachGesture {
val downEvent =
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
var upEventOrCancellation: PointerInputChange? = null
state.upDownDifference = Offset.Zero // Reset
while (upEventOrCancellation == null) {
val event = awaitPointerEvent(pass = PointerEventPass.Initial)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
upEventOrCancellation = event.changes[0]
}
}
state.upDownDifference = upEventOrCancellation.position - downEvent.position
}
}
}
If you don’t want waitUpOrCancel to return null when you move your finger out of bounds copy-paste source code of it and comment the line as i did.
suspend fun AwaitPointerEventScope.waitMyForUpOrCancellation(
pass: PointerEventPass = PointerEventPass.Main
): PointerInputChange? {
while (true) {
val event = awaitPointerEvent(pass)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
return event.changes[0]
}
if (event.changes.fastAny {
val consumed = it.isConsumed
println("Consumed: $consumed")
consumed
// || it.isOutOfBounds(size, extendedTouchPadding)
}
) {
return null // Canceled
}
// // Check for cancel by position consumption. We can look on the Final pass of the
// // existing pointer event because it comes after the pass we checked above.
// val consumeCheck = awaitPointerEvent(PointerEventPass.Final)
// if (consumeCheck.changes.fastAny { it.isConsumed }) {
// println("Consume check consumed...")
// return null
// }
}
}
On real device with this modifier that removes bound and final pass consume check outcome is with only one single pointer or using another pointer while swipe is in action is as
@Preview
@Composable
fun Test() {
val pagerState = rememberPagerState(pageCount = { 5 })
LaunchedEffect(Unit) {
pagerState.interactionSource.interactions.collectLatest { interaction ->
when (interaction) {
is DragInteraction.Start -> println("drag interaction start")
is DragInteraction.Stop -> println("drag interaction stop")
is DragInteraction.Cancel -> println("drag interaction cancel")
}
}
}
var color by remember {
mutableStateOf(Color.Blue)
}
var text by remember {
mutableStateOf("Idle")
}
Column(
modifier = Modifier
) {
Text(text = text, color = color, fontSize = 14.sp, maxLines = 2)
HorizontalPager(
state = pagerState,
) { page ->
val pageColor = when (page) {
0 -> Color.Cyan
1 -> Color.Magenta
2 -> Color.Green
3 -> Color.Yellow
else -> Color.Blue
}
Box(
modifier = Modifier
.background(pageColor)
.fillMaxSize()
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(
requireUnconsumed = false
).also { pointerInputChange ->
println("Is it consumed before ${pointerInputChange.isConsumed}")
pointerInputChange.consume()
println("first down consumed, isScrolling: ${pagerState.isScrollInProgress}")
}
text = "Down, isScrolling: ${pagerState.isScrollInProgress}, $down"
color = Color.Red
val up = waitMyForUpOrCancellation()
?.also { pointerInputChange ->
println("up consumed, isScrolling: ${pagerState.isScrollInProgress}")
}
text = "Up isScrolling: ${pagerState.isScrollInProgress}, $up"
color = Color.Magenta
}
},
contentAlignment = Alignment.Center,
) {
Text(text = "Page index: $page")
}
}
}
}
34