0

我正在使用 Accompanist 的 JetPack Compose Pager,我想知道我如何确切知道我的页面何时显示在屏幕上。就像ViewPager中的 onPageSelected 方法一样。

这是我的代码:

HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.background)
    ) { page ->
         // This method reinvoked many times.

      }

因为目前每个重组都会从 Pager 调用该回调方法。

4

4 回答 4

5

我认为使用会更好

LaunchedEffect(pagerState) {
    snapshotFlow { pagerState.currentPage }.collect { page ->
        // do your stuff with selected page
    }
}
于 2021-09-04T21:57:26.213 回答
1

我们可以在没有任何回调的情况下使用PagerState.

val pagerState = rememberPagerState(pageCount = list.size)
        
        HorizontalPager(state = pagerState) { page ->
            // Our page content
            CardItemView(page, list[page])
        }

// Do your tasks based on the current page selected using pagerState.currentPage
        Toast.makeText(
            LocalContext.current,
            "Page selected ${pagerState.currentPage}",
            Toast.LENGTH_SHORT
        ).show()
于 2022-01-26T18:24:00.890 回答
1

要完成@ysfcyln 解决方案,这里是官方文档:

https://google.github.io/accompanist/pager/#reacting-to-page-changes

完整的例子是:

val pagerState = rememberPagerState()

LaunchedEffect(pagerState) {
    // Collect from the a snapshotFlow reading the currentPage
    snapshotFlow { pagerState.currentPage }.collect { page ->
        AnalyticsService.sendPageSelectedEvent(page)
    }
}

VerticalPager(
    count = 10,
    state = pagerState,
) { page ->
    Text(text = "Page: $page")
}
于 2021-12-06T12:01:49.797 回答
0

使用变量来跟踪

val trigger by remember { mutableStateOf (false) }
HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.background)
    ) { page ->
         // Shown successfully,
         trigger = true //use at other places as a callback to change state
      }
于 2021-07-25T20:38:23.410 回答