Can `HorizontalPager` support circular swiping som...
# compose
p
Can
HorizontalPager
support circular swiping somehow?
g
Yeah, you can supply it with whatever data you want, its just giving you an index to load from.
Set the page count to like Int.MAX_VALUE or something really big, and then get your 'actual page' by division remainder
pagerStatePage % listSize
You can do the same thing with the indicator. Indicator max size = list size, and the current page the same as above. This will give you infinite scroll where when you scroll from the last item, it will loop back to index 0
p
But how do you make this work in negative index direction? Like if you're on index 0 and you try to swipe to index -1. From
HorizontalPager
API, I don't see how would this be achievable, since it looks like it is managing page index for you.
g
start the initial page at Int.MAX_VALUE / 2
👍 1
and then round it down so your 'real page' ends up being zero in that remainder div
that way you have an unreachable number before and an unreachable number after your index.
or just start it at like list.size*1000 or something. Just pick a really big number and you should be fine
remember with the modulus the 'page' that the state object is tracking is irrelevant, because you're just feeding it a bogus value for it to swipe left and right, and then you're actually rendering the remainder of that division against the list size, which will just be 0 -> list.size and will wrap back and fourth in either direction
Copy code
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun InfiniteHorizontalPager(modifier: Modifier = Modifier, size: Int, content: @Composable (page: Int) -> Unit) {
    val pagerState = rememberPagerState(
        pageCount = { size*100000 },
        initialPage = size*50000
    )
    HorizontalPager(modifier = modifier, state = pagerState) { page ->
        content(page%size)
    }
}
There, that will do it. Pager's state didn't like Int.MAX_VALUE, so I jsut picked a large number (100k pages) that no user will ever scroll through.
🍺 1