Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a threshold for LazyColumn/ViewPager before starting to scroll?

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?

like image 635
Mackan Avatar asked Oct 15 '25 03:10

Mackan


1 Answers

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 ->
}
like image 66
Philip Dukhov Avatar answered Oct 19 '25 00:10

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!