【问题标题】:"restore scroll position in android Paging adapter when user go to another fragment or activity from adapter" problem“当用户从适配器转到另一个片段或活动时,在 android Paging 适配器中恢复滚动位置”问题
【发布时间】:2021-10-18 00:06:33
【问题描述】:

当我移动到另一个片段时,如何恢复分页适配器项状态? 我尝试了下面的文章,但没有奏效。 https://medium.com/@florina.muntenescu

private fun loadData() {
        viewModel.apply {
            lifecycleScope.launch{
                viewModel.getMorePopularMovies().collectLatest { pagingData ->
                    dataAdapter.submitData(viewLifecycleOwner.lifecycle, pagingData)

                }
            }
        }

    }

fun getMorePopularMovies() = Pager(
        PagingConfig(pageSize = 3)
) {
    VerticalMoviePagingSource(api, "Popular")
}.flow

【问题讨论】:

  • 我也有同样的问题,回到fragment总是在最前面

标签: android android-recyclerview android-paging scroll-position


【解决方案1】:

尝试在您的 viewModel 代码中添加.cachedIn(viewModelScope)。对于您的情况,您将获得:

  fun getMorePopularMovies() = Pager(
        PagingConfig(pageSize = 3)
) {
    VerticalMoviePagingSource(api, "Popular")
}.flow.cachedIn(viewModelScope)

并尝试添加您的片段:

adapter.stateRestorationPolicy =
        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

如果它不起作用,那么我猜你的代码中还有另一个问题。

【讨论】:

  • 成功了,谢谢:)))
猜你喜欢
  • 2012-08-02
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多