https://kotlinlang.org logo
#compose
Title
# compose
f

Fyodor Danilov

02/27/2024, 2:20 PM
Hello! How can I make repeatable scrolling in Jetpack Compose? What I mean is the following: I have a fixed amount of items (around 20) that I display in LazyVerticalGrid with 2 columns. I want to programatically scroll this grid from time to time. However my list is not infinite and after some time it reaches the end and stops scrolling. What I want is when LazyVerticalGrid is scrolled to the last item the first item will appear again and scrolling will continue. Thanks for any help!
I found the solution
Copy code
@Composable
private fun BackgroundImages(
    modifier: Modifier = Modifier
) {
    val lazyGridState = rememberLazyGridState()
    val resourcesList = remember {
        OnboardingImages
    }

    val scrollHeight = with (LocalDensity.current) {
        (LocalConfiguration.current.screenWidthDp / 2 * 1.5).dp.toPx()
    }

    LaunchedEffect(Unit) {
        while (true) {
            delay(3000L)
            lazyGridState.animateScrollBy(
                value = scrollHeight,
                animationSpec = tween(1500)
            )
        }
    }

    LazyVerticalGrid(
        state = lazyGridState,
        columns = GridCells.Fixed(2),
        userScrollEnabled = false,
        modifier = modifier
            .fillMaxSize()
    ) {
        items(
            count = Int.MAX_VALUE
        ) { index ->
            val painterIndex = index % resourcesList.size

            Image(
                painter = painterResource(resourcesList[painterIndex]),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
            )
        }
    }
}
s

Sergey Y.

02/27/2024, 10:50 PM
Classic and probably the best one.
2 Views