Search code examples
androidandroid-recyclerviewgridlayoutmanager

How to Maintain Scroll position of recyclerView on Screen Rotation


I'm populating the recyclerView with gridlayoutManager. Now I want to save the scroll position on Screen Rotation.

I've tried to do so using onSaveInstanceState and onRestoreInstanceState() as shown in this post :

How to save RecyclerView's scroll position using RecyclerView.State?

Below is my code:

@Override
protected void onSaveInstanceState(Bundle outState) {
    Log.e(TAG, "onSaveInstanceState");
    super.onSaveInstanceState(outState);
    outState.putParcelable(KEY_INSTANCE_STATE_RV_POSITION, 
    gridLayoutManager.onSaveInstanceState());
 }


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {

    Log.e(TAG, "onRestoreInstanceState");
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState!= null){
        Parcelable savedState = 
    savedInstanceState.getParcelable(KEY_INSTANCE_STATE_RV_POSITION);

        movieAdapter.addAll(movieItemList);
        if (savedState!= null){
            gridLayoutManager.onRestoreInstanceState(savedState);
        }
    }
}


//this is my movieAdapter.addAll() method 

public void addAll(List<MovieItem>items){

    movieItems = items;
}


//This is the method to get lists of movies from ViewModel Class

private void loadFavMovies() {
    FavViewModel favViewModel = 
    ViewModelProviders.of(MainActivity.this).get(FavViewModel.class);
    favViewModel.getFavListLiveData().observe(MainActivity.this, new 
    Observer<List<FavlistItem>>() {
        @Override
        public void onChanged(List<FavlistItem> favlistItems) {
            if (!favlistItems.isEmpty()) {
                loadingIndicator.setVisibility(View.GONE);
                movieRecycler.setVisibility(View.GONE);
                favRecycler.setVisibility(View.VISIBLE);
                favAdapter.setFavlistItems(favlistItems);
                Toast.makeText(getApplicationContext(), "Swipe Left Or 
       Right To remove Item",Toast.LENGTH_SHORT).show();
               }else {
                loadingIndicator.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "No Favorite 
      Movies",Toast.LENGTH_SHORT).show();
            }
        }
    });
}

This is the link to GitHub for this project https://github.com/harshabhadra/Movies-Mela


Solution

  • I've tried everything suggested by everyone but finally, this gist work for me

    https://gist.github.com/FrantisekGazo/a9cc4e18cee42199a287

    I just import this in my project and replace the recyclerView provided by default with this "StateFulRecyclerView" and it solved my problem and handle the scroll position automatically during screen rotation or any configuration change. No need to use onSaveInstanceState to maintain scroll positon.