androidandroid-viewpagerandroid-jetpack-compose

How can I align vertical center contents in Android Compose VerticalPager


I am developing an android app using the Jetpack compose.

I should develop a Screen.

It has many Contents Card (Like Feed)

But it should be scrolled sticky. So I used the VerticalPager. When user scrolls, the contents should be scroll to only one by one.

The problem is that the first item is placed in the top of the ui. But from the second content onwards, it must be placed in the center of the screen like this:

enter image description here

I can use below code, and it looks like working fine.

val state = rememberPagerState()
VerticalPager(
    state = state,
    contentPadding = PaddingValues(
        vertical = if (state.canScrollBackward) 120.dp else 0.dp
    ),
    pageSize = PageSize.Fixed(328.dp),
) { idx ->
    FeedUi(feeds[idx])
}

If I set the vertical contentPadding to 120.dp, the content is in centered.

So I use the state.canScrollBackward. state.canScrollBackward means that current position is greater than 0. (1, 2, 3, ... not 0)

It looks like working. But It has two problem.

  1. When I scroll from index 1 to 0, the top UI is not smooth...
  2. The device height are not same. So I cannot set the fixed vertical contentPadding (120.dp)

Is there any better solution?


Solution

  • As far as I understand your question, I think you can use:

    1. fling behavior on VerticalPager

    flingBehavior = rememberSnapFlingBehavior(lazyListState = state)