postmodernist1848
postmodernist1848

Reputation: 27

How to create a wrapping-around list with Jetpack Compose?

For example, I want to create a list that shows elements of an array of 60 * 24 elements for each minute of the day, but I want the user to be able to scroll the 'timeline' from the current time and the list to wrap around when it reaches index 0 or 1439 (for example, show data from last 15 elements and the first 10 after that). I haven't seen this done for some reason.

What I came up with is this (telling LazyColumn that length is Int.MAX_VALUE and just modding the indices while initializing the list index as somewhere in the middle: Int.MAX_VALUE / 2):

private fun listIndex(minutes: Int): Int{
    return (minutes - 10) + Int.MAX_VALUE / 2 - Int.MAX_VALUE / 2 % 1440
}

@Composable
fun TimelineTab(modifier: Modifier = Modifier) {

    val listState = rememberLazyListState(
        initialFirstVisibleItemIndex = listIndex(currentTime().totalMinutes()),
    )

    Box(modifier = modifier.fillMaxSize()) {
        LazyColumn(
            state = listState,
            modifier = Modifier.padding(40.dp)
        ) {
            items(Int.MAX_VALUE) { index ->
                TimelinePoint(gTimeline.arr[index % 1440])
            }
        }
        ...
    }

}

But I am not sure if this is efficient or a good way to do it

Upvotes: 2

Views: 227

Answers (1)

Marat
Marat

Reputation: 1348

val minutes = currentTime().totalMinutes()
val prev = 15
val next = 10
....
items(prev + next + 1) { index ->
    TimelinePoint(gTimeline.arr[(index + minutes - prev + 1440) % 1440])
}

Upvotes: 0

Related Questions