androidkotlinandroid-jetpack-composecoil

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!


Solution

  • You can do the following:

    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)
    }
    

    Here is the result (in the GIF, the interval is 1 sec):

    enter image description here