Search code examples
androidandroid-layoutandroid-recyclerviewonsaveinstancestate

LayoutManager.onSaveInstanceState() not working


I'm trying to save state of my RecyclerView with GridLayoutManager, but when calling onSaveInstanceState() of activity and when I try to call onSaveInstanceState() on layout manager that always return the same object. I trying use method "findFirstVisibleItemPosition", but it always return -1.

RecyclerView has adapter, adapter has some amount of elements, I can scroll them! I don't know why I can't get item position of fully initialized and working component! Please help!

There is my code:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putParcelable(BUNDLE_MOVIES_RECYCLER_VIEW_STATE, mMoviesRecyclerView.getLayoutManager().onSaveInstanceState());

    outState.putInt(BUNDLE_SEGMENT_POSITION, mSelectedFilterPosition);
    outState.putSerializable(BUNDLE_NOW_PLAYING_MOVIE, mNowPlayingMovie);
    outState.putSerializable(BUNDLE_SEGMENTED_MOVIES, mSegmentMovies);
}

Solution

  • Problem was resolved! For saving state of layout manager need call method LayoutManager.onSaveInstanceState() in onPause method of activity. Because in onSaveInstanceState of activity LayoutManager already clear it child from view or just drop layout configuration. Sample of code:

    public class MainActivity extends AppCompatActivity {
    
     RecyclerView recyclerView;
     private Parcelable mLayoutManagerState;
     private static final String LAYOUT_MANAGER_STATE = "LAYOUT_MANAGER_STATE";
    
     @Override
     protected void onPause() {
        super.onPause();
    
        mLayoutManagerState = recyclerView.getLayoutManager().onSaveInstanceState();
     }
    
     @Override
     public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    
        if (savedInstanceState != null) {
            mLayoutManagerState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(mLayoutManagerState);
        }
     } 
    
     @Override
     public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    
        outState.putParcelable(LAYOUT_MANAGER_STATE, mLayoutManagerState);
     }
    }