有没有一种方法可以使双向 Horizo​​ntalPager 自动滚动?

Is there a way to make two way HorizontalPager with auto scroll?

accompanist library 中的 Horizo​​ntalPager 完成了创建简单 ViewPager 的工作;有没有办法在两端无限滑动?

@ExperimentalPagerApi
@Composable
fun AutoScrollPagerHorizontal(d: List<Stem>?) {
    var data: MutableList<Stem> = d?.toMutableList() ?: mutableListOf()

    if (data.isNullOrEmpty()) return
    val pageState = rememberPagerState(pageCount = data.size)
    HorizontalPager(
        state = pageState
    ) {
        Card(
            Modifier
                .height(240.dp)
                .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp)
        ) {
            Image(
                painter = rememberGlidePainter(
                    request = data[it].icon,
                ),
                contentDescription = data[it].title,
                contentScale = ContentScale.FillBounds
            )
        }
    }
}

此代码正确生成 viewpager,但在到达数据的最后一个索引后不会滚动到第 0 个索引。

您可以在可组合项中使用此代码段来自动滚动分页器:

LaunchedEffect(key1 = pagerState.currentPage) {
    launch {
        delay(3000)
        with(pagerState) {
            val target = if (currentPage < pageCount - 1) currentPage + 1 else 0

            animateScrollToPage(
                page = target,
                animationSpec = tween(
                    durationMillis = 500,
                    easing = FastOutSlowInEasing
                )
            )
        }
    }
}

PointerInput 帮助构建了双向寻呼机;以下是对我有用的代码段。

Modifier.pointerInput(Unit) {
                    detectHorizontalDragGestures { change, dragAmount ->
                        change.consumeAllChanges()
                        when {
                            dragAmount < 0 -> {
                                coroutineScope.launch { /* right */
                                    if (pageState.currentPage == data.lastIndex) {
                                        pageState.animateScrollToPage(0)
                                    } else {
                                        pageState.animateScrollToPage(pageState.currentPage + 1)
                                    }
                                }
                            }
                            dragAmount > 0 -> { /* left */
                                coroutineScope.launch {
                                    if (pageState.currentPage == 0) {
                                        pageState.animateScrollToPage(data.lastIndex)
                                    } else {
                                        pageState.animateScrollToPage(pageState.currentPage - 1)
                                    }
                                }
                            }
                        }
                    }
                }