Home > Back-end >  Loop a list in jetpack compose
Loop a list in jetpack compose

Time:12-28

Hello i would like to create a list that would be Circular/Infinite.

By circular or infinite, I mean that when you reach its last element, instead of finishing the list, it would show the first element all over again.

I could just repeat the list 2 or 3 times, but eventually it would still end.

Also worth noting that for other requirements regarding scrolling effects, I am using a HorizontalPager from accompanist.

Anyone knows how to achieve this or if it is even possible?

CodePudding user response:

Yes, you can do that with LazyColumn/LazyRow or Pager which is based on them. You can configure them with "infinite" number of elements and then count proper index in your list using modulo. Something like this:

LazyColumn {
    items(count = Int.Max_VALUE) { index ->
        val item = list[index % list.size]
        Item(item)
    }
}

There is even sample for HorizontalPager in accompanist: https://github.com/google/accompanist/blob/v0.28.0/sample/src/main/java/com/google/accompanist/sample/pager/HorizontalPagerLoopingSample.kt

  • Related