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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With