kotlin 我怎样才能让我的Lazyrow在JetpackCompose中自动滚动?

um6iljoc  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(242)

我有一个项目列表,我使用LazyRow在UI中填充它们。现在我想要的是自动无限滚动行。但没有得到任何线索。

item {
                LazyRow {
                    item { Spacer(modifier = Modifier.width(16.dp)) }
                    items(data.categories) { category ->
                        if(category.discount !=null && category.price!=null) {
                            ItemCard(
                                title = category.name,
                                imageUrl = category.image,
                                discount = category.discount,
                                price = category.price,
                                onClick = onCategoryClick
                            )
                        }
                        Spacer(modifier = Modifier.width(16.dp))
                    }
                }
            }
g6ll5ycj

g6ll5ycj1#

您可以做的是在LazyRow滚动状态下监听可见项计数,并在传递指定值时删除/追加列表的一半,例如:

val scrollState = rememberLazyListState()

val loadMore = remember {
        derivedStateOf {
            val layoutInfo = scrollState.layoutInfo
            val totalItemsNumber = layoutInfo.totalItemsCount
            val lastVisibleItemIndex = (layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0) + 1

            lastVisibleItemIndex > (totalItemsNumber - YOUR_DESIRED_NUMBER)
        }
    }

LaunchedEffect(loadMore) {
  snapshotFlow { loadMore.value }
     .distinctUntilChanged()
     .collect {
         //Remove desired count of items
         //Append the removed items to the end
     }
}

LazyRow(
    state = scrollState
) {
    items.forEach {
         item(key = item.id) { item -> //key is important here
              YourItem(item)
         }
    }
}

相关问题