androidandroid-jetpack-composejetpack-compose-accompanistandroid-jetpack-compose-pager

Compose - Scroll VerticalPager to the top when outer HorizontalPager is scrolled


I have a VerticalPager inside HorizontalPager.

When I scroll VerticalPager down to the Nth page in the 1st page of the HorizontalPager, then scroll to other pages in HorizontalPager, then come back to the 1st page of the HorizontalPager the Nth page I scrolled down to in VerticalPager is saved.

I want always the 1st page of the VerticalPager (not the Nth page I scolled to) to be open whenever HorizontalPager is scrolled.

How can I achieve that?

My code:

val pagerState = rememberPagerState()

HorizontalPager(count = myList.size, state = pagerState) {
    idx ->
    myList[idx].let { cur ->
        val verPagerState = rememberPagerState(initialPage = 0)
        
        VerticalPager(
            count = cur.photos.size,
            state = verPagerState
        ) { page ->

        }
    }
}

Solution

  • Here's how you can scroll it manually when the page is no longer visible.

    I use snapshotFlow, which creates a flow that emit values when the state used inside changes.

    val verPagerState = rememberPagerState(initialPage = 0)
    LaunchedEffect(Unit) {
        snapshotFlow {
            !pagerState.isScrollInProgress
                    && pagerState.currentPage != idx
                    && verPagerState.currentPage != 0
        }.filter { it }
            .collect {
                verPagerState.scrollToPage(0)
            }
    }