【问题标题】:Infinite looping row of images无限循环的图像行
【发布时间】:2022-03-04 07:03:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: kotlin android-jetpack-compose


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2012-02-06
      相关资源
      最近更新 更多