在伴奏寻呼机中自动播放图像

Autoplay Images in Accompanist Pager

我正在使用 Accompanist 实现水平寻呼机。有没有什么优雅的方法让每5秒自动切换一次图片?

否则,我将不得不在视图模型中使用每 5 秒递增一次 currentPage 的通道来伪造手动滑动。老实说,我不太喜欢这种方式。

在 Compose 之前,我曾经实现过 Why Not Image Carousel,它有一个内置的自动播放 属性。

如有任何帮助,我们将不胜感激。谢谢!

您可以执行以下操作:

val images = // list of your images...

val pageState = rememberPagerState(pageCount = images.size)
HorizontalPager(state = pageState) {
  // Your content...
}

// This is the interesting part, when your page changes,
// the LaunchedEffect will run again
LaunchedEffect(pageState.currentPage) {
    delay(3000) // wait for 3 seconds.
    // increasing the position and check the limit
    var newPosition = pageState.currentPage + 1
    if (newPosition > images.lastIndex) newPosition = 0
    // scrolling to the new position.
    pageState.animateScrollToPage(newPosition)
}

结果如下(在GIF中,间隔为1秒):