0

我模仿了codelab,实现了getRefreshKey()方法,但是由于params.loadSize3*PAGE_SIZE在刷新之后(也就是删除一个item或者编辑一个item),所以我的recyclerview大概率不会回到原来的位置。我应该怎么办?这是我的寻呼源:

class PasswordPagingSource2(
        val type: String,
        val service: PasswordService,
        val PAGE_SIZE:Int) :
        PagingSource<Int, Any>() {

    private  val PAGE_INDEX = 0


    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Any> {
        val page = params.key ?: PAGE_INDEX

        return try {


            val list =
                    service.getPasswords(
                    "{\"type\":\"$type\"}",
                    params.loadSize, page * PAGE_SIZE).items
            val preKey = if (page > 0) page - 1 else null
            val nextKey = if (list.isNotEmpty()) page + (params.loadSize/PAGE_SIZE)else null
            return LoadResult.Page(data =list, prevKey = preKey, nextKey = nextKey)
        } catch (exception: IOException) {
            return LoadResult.Error(Throwable("IO Error"))
        } catch (exception: HttpException) {
            return LoadResult.Error(Throwable("Network Error"))
        }

    }


    override fun getRefreshKey(state: PagingState<Int, Any>): Int? {
      
        val page = state.anchorPosition?.let { anchorPosition->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                    ?:state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
        return page
    }


}
4

1 回答 1

0

您有责任确保initialLoadSize将加载足够的项目以覆盖视口,以便在失效时,您将加载足够的项目,以便前一个列表和失效后的初始刷新重叠,以便DiffUtil帮助您恢复滚动位置。

如果你想保持pageSize不变,你可以改为修改initialLoadSizePagingConfig根据经验,您希望它一次加载至少 2 倍可见项目数,包括最后一个PagingState.anchorPosition.

于 2021-09-11T15:30:15.327 回答