Hari Nikesh R
Hari Nikesh R

Reputation: 83

Horizonal Pager offset is not coming to center after scrolling

I wrote a logic to scroll an image every 5 seconds. I also set the pageoffset to 0 while animating. But the currentPageOffset is not coming as expected as 0. It is automatically deviated to negative and positive, but expected is 0.

Log that I reproduced, Logs for currentOffset

Code that I used for scroll for every 5 seconds.

while (true) {
      delay(5000)
      Timber.i("scroll pageState.currentPageOffsetFraction -> ${pageState.currentPageOffsetFraction}")
      Timber.i("scroll pageState.currentPage -> ${pageState.currentPage}")
      Timber.i("scroll pageState.pageCount -> ${pageState.pageCount}")
      if (pageState.currentPage + 1 < viewModel.total) {
        pageState.animateScrollToPage(page = pageState.currentPage + 1, pageOffsetFraction = 0f)
      } else {
        pageState.scrollToPage(viewModel.initialPager)
      }
    }

Upvotes: 1

Views: 124

Answers (2)

Frank
Frank

Reputation: 12300

Yes, it's a rounding bug in the latest version of PagerState, I think.

What I do to fix it:

val currentPageOffsetFraction = remember { derivedStateOf { pagerState.currentPageOffsetFraction.absoluteValue } }
val settledOnAPage = currentPageOffsetFraction.value <= 0.01f
LaunchedEffect(settledOnAPage) {
    if (settledOnAPage) pagerState.scrollToPage(pagerState.targetPage)
}

This jumps the last bit, which is so small that you do not notice the jump, but you do see it centered correctly on the screen.

Upvotes: 0

shahid17june
shahid17june

Reputation: 1577

As per android documents currentPageOffsetFraction value is correct value can be -0.5 to 0.5.

ref:- enter image description here

you can use the absoluteValue pageoffset to animate the list:-

pageState.animateScrollToPage(page = pageState.currentPage + 1, pageOffsetFraction = pageState.currentPageOffsetFraction.absoluteValue)

Upvotes: 0

Related Questions