如何在 Android Jetpack Compose 中结合使用 LazyColumn stickyHeader 和 Paging?
Posted
技术标签:
【中文标题】如何在 Android Jetpack Compose 中结合使用 LazyColumn stickyHeader 和 Paging?【英文标题】:How to use LazyColumn stickyHeader in combination with Paging in Android Jetpack Compose? 【发布时间】:2021-08-14 13:32:08 【问题描述】:我已经用Paging 实现了LazyColumn
,但我现在也在尝试添加sticky headers。
stickyHeader()
函数在 items()
范围内不可用,所以我看不出它应该如何工作。
@Composable
fun MovieList(movies: Flow<PagingData<Movie>>)
val lazyMovieItems: LazyPagingItems<Movie> = movies.collectAsLazyPagingItems()
LazyColumn
// TODO: Add sticky headers
items(lazyMovieItems) movie ->
MovieItem(movie = movie!!)
如何添加stickyHeader
s?
【问题讨论】:
【参考方案1】:@Composable
fun MovieList(movies: Flow<PagingData<Movie>>)
val lazyMovieItems = movies.collectAsLazyPagingItems()
LazyColumn
val itemCount = lazyMovieItems.itemCount
var lastCharacter: Char? = null
for (index in 0 until itemCount)
// Gets item without notifying Paging of the item access,
// which would otherwise trigger page loads
val movie = lazyMovieItems.peek(index)
val character = movie?.name?.first()
if (movie !== null && character != lastCharacter)
stickyHeader(key = character)
MovieHeader(character)
item(key = movie?.id)
// Gets item, triggering page loads if needed
val movieItem = lazyMovieItems.getAsState(index).value
Movie(movieItem)
lastCharacter = character
【讨论】:
getAsState
在 alpha14 中已弃用,现在您可以直接将索引用作lazyMovieItems[index]。以上是关于如何在 Android Jetpack Compose 中结合使用 LazyColumn stickyHeader 和 Paging?的主要内容,如果未能解决你的问题,请参考以下文章
Android Jetpack Navigation:如何在 OnNavigatedListener 中获取目的地的片段实例?