Scroll Two Lazy Scrollers Together

Issue

This question has been asked before, but in different forms, regarding some specific use cases, and so far there has been no answer. I finally got it working, so I am sharing this here, but this should not be marked as a duplicate since all the previous questions specify specific stuff, like Columns with scrollable Modifiers, or LazyRows, but this will resolve all the issues in general, I mean all the lazy-scrollers, and hopefully even scrollable containers in general. I’ll post the answer so this is just a piece of knowledge that I wished to share with the community, also, any improvements are welcome, of course.

Solution

This is the full working solution:-

@Composable
fun DUME() {

    val stateRowX = rememberLazyListState() // State for the first Row, X
    val stateRowY = rememberLazyListState() // State for the second Row, Y

    Column { // Placing two Lazy Rows one above the other for the example

        LazyRow(state = stateRowY) {
            items(LoremIpsum(10).values.toList()) {
                Text(it)
            }
        }

        LazyRow(state = stateRowX) {
            items(LoremIpsum(10).values.toList()) {
                Text(text = it)
            }
        }

    }

    //This might seem crazy

    LaunchedEffect(stateRowX.firstVisibleItemScrollOffset) {
        stateRowY.scrollToItem(
            stateRowX.firstVisibleItemIndex,
            stateRowX.firstVisibleItemScrollOffset
        )
    }

    LaunchedEffect(stateRowY.firstVisibleItemScrollOffset) {
        stateRowX.scrollToItem(
            stateRowY.firstVisibleItemIndex,
            stateRowY.firstVisibleItemScrollOffset
        )
    }
}

The items import here is : androidx.compose.foundation.lazy.items, this accepts a list instead of a number (the size).

Answered By – Richard Onslow Roper

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published