Jetpack Compose 中带有分页库的粘性标头

Cil*_*nco 2 android android-paging-library android-jetpack-compose

我目前正在使用新的 Jetpack compose UI 工具包,我非常喜欢它。我无法弄清楚的一件事是如何stickyHeadersLazyColumn由分页库填充的a中使用。文档中的非分页示例是:

val grouped = contacts.groupBy { it.firstName[0] }

fun ContactsList(grouped: Map<Char, List<Contact>>) {
    LazyColumn {
        grouped.forEach { (initial, contactsForInitial) ->
            stickyHeader {
                CharacterHeader(initial)
            }

            items(contactsForInitial) { contact ->
                ContactListItem(contact)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我使用的是分页库,groupedBy因此我无法使用它,因此我尝试使用该insertSeparators函数PagingData并像这样自己插入/创建标头(请忽略遗留Date代码,它仅用于测试):

// On my flow
.insertSeparators { before, after ->
        when {
            before == null -> ListItem.HeaderItem(after?.workout?.time ?: 0)
            after == null -> ListItem.HeaderItem(before.workout.time)
            (Date(before.workout.time).day != Date(after.workout.time).day) ->
                ListItem.HeaderItem(before.workout.time)
            // Return null to avoid adding a separator between two items.
            else -> null
        }
    }

// In my composeable
LazyColumn {
    items(workoutItems) {
        when(it) {
            is ListItem.HeaderItem -> this@LazyColumn.stickyHeader { Header(it) }
            is ListItem.SongItem -> WorkoutItem(it)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这会生成我所有项目的列表,并在末尾附加标题项目。任何想法stickyHeader在使用分页库时使用该功能的正确方法是什么?

Cil*_*nco 5

我通过查看items函数的源代码让它工作:你不能stickyHeaderitems函数内调用。根本不需要修改 PagingData 流。只需使用 peek 获取下一个项目而不触发重新加载,然后对其进行布局:

LazyColumn {
    var lastWorkout: Workout? = null

    for(index in workoutItems.indices) {
        val workout = workoutItems.peek(index)

        if(lastWorkout?.time != workout?.time) stickyHeader { Header(workout) }
        item { WorkoutItem(workoutItems.getAsState(index).value) } // triggers reload

        lastWorkout = workout 
    }
}
Run Code Online (Sandbox Code Playgroud)