android - 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!
解决方案
您可以执行以下操作:
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 秒):
推荐阅读
- c++ - OpenCV C++ 中的范围错误
- ios - Firestore - 在 Tableview 中显示数据
- java - Spring 缓存是如何工作的?
- python - python sklearn pipiline fit:“AttributeError:未找到下限”
- java - 线程完成时如何测试结果 - java
- javascript - 在多个元素上使用 addEventListener,避免在未找到特定元素时出现 TypeError
- sql - 使用 sqlite3 如何在 SQL-db(或其 CSV)中设置一列的宽度
- android - 音轨 setVolume - 最小值
- automapper - 与实体框架一起使用时如何调试自动映射器映射是否正确
- c++ - FILE *在不同的函数c ++中初始化