How to implement 'Snap to center' feature for lists in Jetpack Compose?
W

4

13

In EpoxyRecyclerView with Horizontal LinearLayout there is a Snap to center feature which works like, If i scroll the list with good speed, it keeps on scrolling until it slows down and rests with an item at center. And if I scroll slowly and lift up the finger, then the next item spans/moves to center of screen. One thing you have to understand that, this is not a Pager. Pager automatically snaps the next item only. But I cannot scroll like a free rolling...

You can see this gif as an example

enter image description here

So, I'm looking for such snapping feature in Jetpack Compose. Is this possible yet? If yes, how to achieve this?

Wormhole answered 29/7, 2021 at 6:49 Comment(3)
HorizontalViewPager.Lavabo
@Lavabo the the library you gave is a normal viewpager which is clearly mentioned that is not what I'm looking for... I also need the list to scroll freely several itemsWormhole
Did you find solution?Mcginley
P
8

If you use Compose 1.3 you can check the SnapFlingBehavior here

Perreault answered 21/11, 2022 at 15:44 Comment(0)
M
7

You can use this library as well https://github.com/chrisbanes/snapper

https://chrisbanes.github.io/snapper/

val lazyListState = rememberLazyListState()

LazyRow(
    state = lazyListState,
    flingBehavior = rememberSnapperFlingBehavior(lazyListState),
) {
    // content
}
Mandibular answered 11/4, 2022 at 8:14 Comment(1)
This does not work with scrolling on Desktop.Vince
D
6

Starting with compose 1.3.0 you can use the FlingBehavior that performs snapping of items to a given position:

val state = rememberLazyListState()

LazyRow(
    modifier = Modifier.fillMaxSize(),
    verticalAlignment = Alignment.CenterVertically,
    state = state,
    flingBehavior = rememberSnapFlingBehavior(lazyListState = state)
) {
  //item content
}
Dibru answered 20/12, 2022 at 17:37 Comment(0)
C
4

You can try out this library: https://github.com/aakarshrestha/compose-pager-snap-helper The code will look as follows (using LazyRow for listing the items)

ComposePagerSnapHelper(
        width = 320.dp, //required
        content = { listState -> //this param is provided by the method itself, add this param below.
            LazyRow(
                state = listState, //add listState param
            ) {
                items(count = count) { item ->
                    //Put your Items Composable here
                }
            }
        }
    )
Chadburn answered 22/8, 2021 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.