使用 PagedListAdapter 时对数组项进行排序?

MrT*_*rTy 6 custom-paging android-paging

我正在使用Paging 库

目前,我想通过 PagedListAdapter 中的描述对项目进行排序(使用SortList),但我还没有想出如何去做。

使用 PagedListAdapter 时如何对元素进行排序?谢谢你。

kip*_*ip2 6

我也遇到了这个问题,并且很惊讶PagedList似乎没有一种直接的方法来对项目进行排序。以下是我如何使用DataSourcemapByPage()实现所需的效果:

/** sorts MyItems by timestamp in descending order */
private fun DataSource.Factory<Long, MyItem>.sortByDescTime(): DataSource.Factory<Long, MyItem> {
return mapByPage {
    myItemsList.sortedWith(compareByDescending { item -> item.timeStamp })
  }
}
Run Code Online (Sandbox Code Playgroud)

即,输入mapByPage()应该是您的排序函数(取决于您的设置,我的使用 Kotlin 扩展和 lambda 语法对目标列表中的项目进行排序 - 使用Collections.sortedWith()

然后,在数据源上使用我的扩展功能对获取的项目进行排序:

fun fetchItems(userId: Long): LiveData<PagedList<MyItem>> {
    val itemDataSource = itemAPIService.getItems(userId).sortByDescTime()
    val itemPagedList = LivePagedListBuilder(itemDataSource, 10).build()
    return itemPagedList
}
Run Code Online (Sandbox Code Playgroud)