androidandroid-recyclerviewandroid-pagingscroll-position

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


How can ı restore paging adapter item state when ı move to another fragment? I tried article below but it didnt work. 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

Solution

  • Try adding .cachedIn(viewModelScope) in your viewModel code. For your case you will get:

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

    And try adding in your fragment:

    adapter.stateRestorationPolicy =
            RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
    

    If it doesn't work then there is another problem in your code, I guess.