【问题标题】:In Paging3, after deleting the item, how to return the recyclerview to its original position?在Paging3中,删除item后,recyclerview如何恢复到原来的位置?
【发布时间】:2021-03-26 05:31:18
【问题描述】:

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

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
    }


}

【问题讨论】:

    标签: android android-studio android-jetpack android-paging-3


    【解决方案1】:

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

    如果您想保持pageSize 不变,可以改为在PagingConfig 中修改initialLoadSize。根据经验,您希望它在最后一个 PagingState.anchorPosition 之前和之后一次加载至少 2 倍可见项目数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多