【问题标题】:How to use LazyColumn stickyHeader in combination with Paging in Android Jetpack Compose?如何在 Android Jetpack Compose 中结合使用 LazyColumn stickyHeader 和 Paging?
【发布时间】:2023-03-05 05:26:01
【问题描述】:

我已经用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!!)
        }
    }
}

如何添加stickyHeaders?

【问题讨论】:

    标签: android kotlin android-jetpack android-jetpack-compose android-paging


    【解决方案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]。
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2022-07-29
    • 2021-06-01
    • 2022-09-29
    • 2021-06-04
    • 1970-01-01
    • 2022-11-10
    • 2022-08-22
    相关资源
    最近更新 更多