首页 > 解决方案 > 如何通过自动滚动回顶部来刷新分页适配器?

问题描述

这是我第一次使用分页库 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()

标签: androidandroid-paging-3

解决方案


您需要实施getRefreshKey以返回非空结果。

getRefreshKeyPaging 使用它来获取刷新的键,如果返回 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
      }
    }
  }
}

推荐阅读