dgkat
dgkat

Reputation: 43

How to create vertical infinite carousel in Jetpack Compose?

I'm trying to build a scrollable column (preferably LazyColumn) that will start re-showing the first items again after I scroll to the end. For example, see this alarm clock that will cycle from 00..59 and then will smoothly keep scrolling from 0 again.

I've tried a normal LazyColumn that will show 58,59,00..59,00,01 and snap to start after I'm done scrolling (reaching 59) but it looks "cheap".

Upvotes: 3

Views: 4535

Answers (2)

Jonny S.
Jonny S.

Reputation: 1

I created something similar to what you are working on. If you set the pageCount to Int.MaxValue, you can then find the middle number that is module(divisible by of the size of items)

fun EndlessCarousel(){
    ...
    val pageCount = Int.MAX_VALUE
    val items = List<Int>
    val pagerState = rememberPagerState((pageCount / 2 / items.size) * items.size)
    HorizontalPager(
    modifier = Modifier,
    pageCount = pageCount,
    state = pagerState
    ...
    )

hope this helps :)

Upvotes: 0

Dyvoker
Dyvoker

Reputation: 2789

@Composable
fun CircularList(
    items: List<String>,
    modifier: Modifier = Modifier,
    isEndless: Boolean = false,
    onItemClick: (String) -> Unit
) {
    val listState = rememberLazyListState(
        if (isEndless) Int.MAX_VALUE / 2 else 0
    )

    LazyColumn(
        state = listState,
        modifier = modifier
    ) {
        items(
            count = if (isEndless) Int.MAX_VALUE else items.size,
            itemContent = {
                val index = it % items.size
                Text(text = items[index])    // item composable
            }
        )
    }
}

Upvotes: 8

Related Questions