4

I'm using the experimental viewpager for Jetpack compose which is built upon LazyColumn/Row.

What I'm trying to do is to set some threshold of how much I need to move my finger before it starts to scroll to next page. The default behaviour is that as soon as I move my finger it starts to scroll, but I want to have a larger threshold of how much I need to move the finger before any visual scrolling occur. I've looked at the FlingBehaviour parameter, but I don't see how to use that to accomplish what I want. (Or at least add some more "resistance" to flip between the pages, so it's not so sensitive)

Have you got any ideas?

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Mackan
  • 1,305
  • 2
  • 17
  • 30

1 Answers1

4

This threshold is controlled by the flingBehavior argument.

PagerDefaults.flingBehavior(pagerState) provides paging work, currently only animations are configurable, so you can't just provide your own instead behavior instead. But you can wrap it like this:

private class FlingBehaviourMultiplier(
    private val multiplier: Float,
    private val baseFlingBehavior: FlingBehavior
) : FlingBehavior {
    override suspend fun ScrollScope.performFling(initialVelocity: Float): Float {
        return with(baseFlingBehavior) {
            performFling(initialVelocity * multiplier)
        }
    }
}

@Composable
fun rememberFlingBehaviorMultiplier(
    multiplier: Float,
    baseFlingBehavior: FlingBehavior
): FlingBehavior = remember(multiplier, baseFlingBehavior) {
    FlingBehaviourMultiplier(multiplier, baseFlingBehavior)
}

Usage:

val pagerState = rememberPagerState()
HorizontalPager(
    count = 10,
    state = pagerState,
    flingBehavior = rememberFlingBehaviorMultiplier(
        multiplier = 0.5f,
        baseFlingBehavior = PagerDefaults.flingBehavior(pagerState)
    ),
    modifier = Modifier
) { page ->
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • There is no PagerDefaults.flingBehavior() method anymore... This answer needs to be revisited. (Version 0.18.0) – Ali_Waris Jan 10 '22 at 14:45
  • @Ali_Waris It's still there, maybe you have an error because it's experimental? Also 0.18.0 is not the latest version, you can check it [here](https://github.com/google/accompanist/releases) – Phil Dukhov Jan 11 '22 at 01:24
  • I know, 0.18.0 is not the latest, but due to some issues in the latest version, i cannot move to the versions 0.18.0+ – Ali_Waris Jan 11 '22 at 05:19
  • 1
    Is there a way to reduce the amount of pixels (or % of screen) need to be scrolled before the next/prev page will be selected? Currently I need to scroll more than 50% of the page, so that the next/prev one is selected...I would like to only scroll 20% or so...50% on a landscape tablet is a verrrry long swipe.... – jpm May 31 '22 at 08:39