This is a conceptual issue. Sorry if it is a simple question, I start to learn Android few days ago.
I was trying to save the state of a recyclerview when the user out of the activity. And I read some articles about this.
In this article https://panavtec.me/retain-restore-recycler-view-scroll-position the methods are :
protected Parcelable onSaveInstanceState();
protected void onRestoreInstanceState(Parcelable state);
In this other article RecyclerView store / restore state between activities the methods are:
protected void onSaveInstanceState(Bundle state)
protected void onRestoreInstanceState(Bundle state)
These two articles pretend to answer the same question, how to restore the state of a recyclerview.
Questions:
1 - The first article implements these methods on a layoutManager!? So, I'm using a default GridLayoutManager, so to implement save and restore instance in the GridLayoutManager I should create my own class extending the default class?
2 - I can implement these methods in the layoutmanager regardless of implementing them in the activity?
3 - Where is the correct place to implement these methods? or is there a official answer to the question: "How restore the state of a recyclerview?"
I am looking for opinions on these three questions, not a full implementation.
If you look at both the article and the SO post they do not implement anything inside the
LayoutManager, they just use methods that already exist. If you look in the documentation page for the GridLayoutManager there are already both aonSaveInstanceState()and aonRestoreInstanceState (Parcelable state)methods (these two methods are the "convenient API" the blog mentions at the start).As I'm sure you've noticed
GridLayoutManagerinherits fromLinearLayoutManagerofficial documentation of LinearLayoutManager.onSaveInstanceState():official documentation of LinearLayoutManager.onRestoreInstanceState (Parcelable state) Very incomplete but you can tell that it uses the same
Parcelableparameter returned by LinearLayoutManager.onSaveInstanceState()To be clear: no need to re-implement the LayoutManager. I don't see why you would need to do that, the methods are there and ready to use. The Activity methods of the same name are what you need to implement.
The correct place to do this is the Activity's lifecycle methods, these will be called at the appropriate times to save and restore your
LayoutManagerstate. Quoting the SO answer you mentioned:I haven't seen any official documentation about specifically restoring the RecyclerView/LayoutManager state but the lifecycle subject is a very important one in Android. I believe that after fully understanding this one can make the right decisions regarding specific use-cases.
Hope this helps ;)