android - 如何通过自动滚动回顶部来刷新分页适配器?
问题描述
这是我第一次使用分页库 3。这是我的 PagingSource 文件,对于 API,我们必须使用游标来进行分页,每次刷新适配器时它都会滚动回列表顶部,是否有如何在不滚动到顶部的情况下刷新列表?
class SearchProductDataSource(
private val searchFilter: SearchFilter,
private val searchProductsUseCase: SearchProductsUseCase
) : PagingSource<String, Product>() {
override fun getRefreshKey(state: PagingState<String, Product>): String? {
return null
}
override suspend fun load(params: LoadParams<String>): LoadResult<String, Product> {
try {
val currentKey = params.key
val newFilter: SearchFilter = searchFilter.copy(afterCursor = currentKey)
val result = searchProductsUseCase(newFilter, params.loadSize)
val nextKey = if (result?.pageInfo?.hasNextPage == true)
result.cursor
else
null
return LoadResult.Page(result.list, currentKey, nextKey)
} catch (e: Exception) {
Timber.e(e)
return LoadResult.Error(e)
}
}
}
这就是我在更新愿望清单后调用刷新方法的方式。
adapter.refresh()
解决方案
您需要实施getRefreshKey
以返回非空结果。
getRefreshKey
Paging 使用它来获取刷新的键,如果返回 null,这就是将传递给 的内容params.key
,在这种情况下,它看起来像返回第一页。
类似于以下内容的内容可能对您有用:
override fun getRefreshKey(state: PagingState<String, Product>): String? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.let { anchorPage ->
val pageIndex = pages.indexOf(anchorPage)
if (pageIndex == 0) {
null
} else {
pages[pageIndex - 1].nextKey
}
}
}
}
推荐阅读
- javascript - 在 ngOnInit() 内部使用 ngOnInit() 外部的函数
- mysql - 如何使用 SELECT LAST_INSERT_ID(); 在mysql例程中插入语句后?
- python - 排序、排名、groupby 和 sum 组合 -> Python pandas
- c# - Sqlite 使用过程/触发器附加数据库,我将能够从 c# 运行它
- maven - 如何在每个环境中配置 Maven Surefire 中的环境变量?
- uml - 我怎么能说数组中的所有元素都必须在 OCL 中具有某些属性?
- mongodb - 使用 MongoRepository 更新实体时修改的计数
- r - 内联显示文件输入和操作按钮
- python - exchangelib 会议从房间电子邮件中获取日历
- django - 获取和插入 Django 在 Angular 中设置的 CSRF cookie 的值