Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView store / restore state between activities

I'm migrating my ListViews to RecyclerViews. With listviews I used the common technique described here to store and restore scroll position between activities.

How to do the same with RecyclerViews? the RecyclerView.onSaveInstanceState() seem to have protected access, so can't be used directly.

like image 635
khusrav Avatar asked Jan 30 '15 12:01

khusrav


1 Answers

Ok, so to answer my own question. As I understand it, since they've decoupled the layout code and the view recycling code (thus the name), the component responsible one for holding layout state (and restoring it) is now the LayoutManager used in your recyclerview.

Thus, to store state you use same pattern, but on the layout manager and not the recyclerview:

protected void onSaveInstanceState(Bundle state) {      super.onSaveInstanceState(state);       // Save list state      mListState = mLayoutManager.onSaveInstanceState();      state.putParcelable(LIST_STATE_KEY, mListState); } 

Restore state in the onRestoreInstanceState():

protected void onRestoreInstanceState(Bundle state) {     super.onRestoreInstanceState(state);      // Retrieve list state and list/item positions     if(state != null)         mListState = state.getParcelable(LIST_STATE_KEY); } 

Then update the LayoutManager (I do in onResume()):

@Override protected void onResume() {     super.onResume();      if (mListState != null) {         mLayoutManager.onRestoreInstanceState(mListState);     } } 
like image 133
khusrav Avatar answered Sep 30 '22 17:09

khusrav