"restore scroll position in android Paging adapter when user go to another fragment or activity from adapter" 问题

"restore scroll position in android Paging adapter when user go to another fragment or activity from adapter" problem

当我移动到另一个片段时,如何恢复分页适配器项目状态? 我试过下面的文章,但没有用。 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

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

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

并尝试添加您的片段:

adapter.stateRestorationPolicy =
        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

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