无限循环的图像行

Infinite looping row of images

如何创建一个以固定速度自动滚动并围绕图像列表内容循环的滚动行?

我有下面定义的惰性图像行,但还没有找到循环播放它的好方法(如轮播)。

var images: List<String> = listOf()
repeat(8) {
    images = images.plus("https://place-puppy.com/300x300")
}
val state = rememberLazyListState()
LazyRow(
    modifier = modifier.fillMaxWidth(),
    state = state
) {
    items(count = images.size) { i ->
        val image = images.get(i)
        Column(
            modifier = Modifier
                .width(40.dp)
                .aspectRatio(1f)
        ) {
            Image(
                painter = rememberImagePainter(image),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxSize()
        }
    }
}

首先,创建一个无限 auto-scrolling 效果,只要可组合项处于活动状态并显示,该效果就会 运行:

LazyRow() {
  ....
}
LaunchedEffect(Unit) {
    autoScroll(lazyListState)
}
private tailrec suspend fun autoScroll(lazyListState: LazyListState) {
    lazyListState.scroll(MutatePriority.PreventUserInput) {
        scrollBy(SCROLL_DX)
    }
    delay(DELAY_BETWEEN_SCROLL_MS)

    autoScroll(lazyListState)
}

private const val DELAY_BETWEEN_SCROLL_MS = 8L
private const val SCROLL_DX = 1f

其次,相应地更新项目在列表中的位置:

    val lazyListState = rememberLazyListState()

    LazyRow(
        state = lazyListState,
        modifier = modifier,
    ) {
        items(images) {
            ...

            if (it == itemsListState.last()) {
                val currentList = images

                val secondPart = currentList.subList(0, lazyListState.firstVisibleItemIndex)
                val firstPart = currentList.subList(lazyListState.firstVisibleItemIndex, currentList.size)

                rememberCoroutineScope().launch {
                    lazyListState.scrollToItem(0, maxOf(0, lazyListState.firstVisibleItemScrollOffset - SCROLL_DX.toInt()))
                }

                images = firstPart + secondPart
            }
        }
    }

这应该会给你循环行为。

致谢:https://proandroiddev.com/infinite-auto-scrolling-lists-with-recyclerview-lazylists-in-compose-1c3b44448c8