首页 > 解决方案 > Autoplay Images in Accompanist Pager

问题描述

I'm implementing an horizontal pager with Accompanist. Is there an elegant way to automatically switch the images every 5 seconds?

Otherwise, I'd have to fake a manual swipe by using a channel in the viewmodel that increments the currentPage every 5 seconds.. which, to be honest, I'm not quite a fan of.

Before Compose, I used to implement the Why Not Image Carousel, which has a built-in autoplay property.

Any help would be appreciated. Thx!

标签: androidkotlinandroid-jetpack-composecoil

解决方案


您可以执行以下操作:

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 秒):

在此处输入图像描述


推荐阅读