1

I'm using com.google.accompanist:accompanist-pager to implement infinite scroll of pages. I implemented everything as described in HorizontalPagerLoopingSample. I need show my pager starting from third page. But when I set initialPage = 2 HorizontalPager showing wrong page. In the sample to show the first page is set initalPage = Int.MAX_VALUE / 2. Is it possible to calculate real specific position with infinite pager ?

I try to do something like this:

val positionFromIWantToStart = 2
 val startIndex = (Int.MAX_VALUE / 2) + positionFromIWantToStart
 val pagerState = rememberPagerState(initialPage = startIndex)

But this is not working correct, HorizontalPager always show first page.

Please help me.

testivanivan
  • 967
  • 13
  • 36

1 Answers1

4

I think this is more a math question :)

I think it should be something like this:

val yourList = (1..5).map { it.toString() }
val colors = listOf(Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Magenta)

val positionFromIWantToStart = 3
val itemsCount = yourList.size

val numPages = Int.MAX_VALUE / itemsCount
val startPage = numPages / 2
val startIndex = (startPage * itemsCount) + positionFromIWantToStart

val pagerState = rememberPagerState(initialPage = startIndex)

HorizontalPager(
    state = pagerState,
    count = Int.MAX_VALUE
) { index ->
    val page = index % itemsCount
    Text(
        text = "Page ${yourList[page]}",
        modifier = Modifier
            .fillMaxSize()
            .background(colors[page]),
        textAlign = TextAlign.Center
    )
}
nglauber
  • 18,674
  • 6
  • 70
  • 75