有没有办法制作具有自动滚动功能的双向 Horizo​​ntalPager?

Ali*_*ris 1 horizontal-scrolling kotlin android-jetpack-compose

伴奏库中的 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
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Sau*_*rat 7

您可以在可组合项中使用此代码片段来自动滚动寻呼机:

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
                )
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)