Android Jetpack Compose中带有分页库的粘性头文件
我目前正在使用新的Jetpack compose UI工具包,我非常喜欢它。有一件事我搞不清楚,那就是如何在由分页库填充的Android Jetpack Compose中带有分页库的粘性头文件,android,android-jetpack-compose,android-paging-library,Android,Android Jetpack Compose,Android Paging Library,我目前正在使用新的Jetpack compose UI工具包,我非常喜欢它。有一件事我搞不清楚,那就是如何在由分页库填充的LazyColumn中使用stickyHeaders。来自的非分页示例是: 但这会生成一个所有“我的项目”的列表,标题项目会附加在末尾。您知道使用分页库时使用stickyHeader函数的正确方法是什么吗?我通过查看items函数的源代码找到了它:您不能在items函数中调用stickyHeader。根本不需要修改分页数据流。只需使用peek获取下一个项目,而无需触发重新加载
LazyColumn
中使用stickyHeaders
。来自的非分页示例是:
但这会生成一个所有“我的项目”的列表,标题项目会附加在末尾。您知道使用分页库时使用
stickyHeader
函数的正确方法是什么吗?我通过查看items
函数的源代码找到了它:您不能在items
函数中调用stickyHeader
。根本不需要修改分页数据流。只需使用peek获取下一个项目,而无需触发重新加载,然后对其进行布局:
LazyColumn {
val itemCount = workoutItems.itemCount
var lastWorkout: Workout? = null
for(index in 0 until itemCount) {
val workout = workoutItems.peek(index)
if(lastWorkout ?.time != workout?.time) stickyHeader { Header(workout) }
item { WorkoutItem(workoutItems.getAsState(index).value) } // triggers reload
lastWorkout = workout
}
}
我相信您的代码中的问题是您正在呼叫
this@LazyColumn
从一个LazyItemScope
的内部
我也尝试了insertseparator
,得到了这个工作懒散的列代码:
LazyColumn{
对于(在0中索引,直到照片。itemCount){
当(val peek数据=photos.peek(索引)){
是字符串吗?->stickyHeader{
正文(
text=(photos.getAsState(index).值为?字符串).orEmpty(),
)
}
是照片?->项(键={peekData?.id}){
val photo=photos.getAsState(索引)。值为?photo
...
}
}
}
}
谢谢您的帮助。数据显示正确,但当我将新项目滚动到视图(或向上滚动)时,某些项目的内容将不可见。我认为这与compose没有检测到它在屏幕上有关,所以它只是跳过渲染。这是您也经历过的吗?我没有,请确保调用workutitems.getAsState(index).value
,因为这会触发从分页库重新加载。不要将您从peek
中获得的物品用于布局。
// 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)
}
}
}
LazyColumn {
val itemCount = workoutItems.itemCount
var lastWorkout: Workout? = null
for(index in 0 until itemCount) {
val workout = workoutItems.peek(index)
if(lastWorkout ?.time != workout?.time) stickyHeader { Header(workout) }
item { WorkoutItem(workoutItems.getAsState(index).value) } // triggers reload
lastWorkout = workout
}
}