2

I have a simple activity with two fragment: main (contains a list of items) and detail. Details screen is a fragment, which is displayed when an item is clicked in main list. DetailFragment is being shown using replace().

After navigating back from detail screen I would like to have exact same scroll position in RecyclerView that I left it with.

As long as replace() initiates onDestroyView() and onCreateView() cycle to happen for MainFragment, after coming back from DetailFragment the RecyclerView has a scroll position of 0 (at the top), because this is a brand new RecyclerView which has no connection to the one that was there before leaving to DetailFragment.

replace()ing fragment does not initiate onSaveInstanceState() to be called, that's why using techniques outlined here are not applicable.

I wonder what is the correct way of handling this use-case?

Of course I can save the position on onDestroyView() and later manually scroll to that position, but maybe I'm missing some obvious solution?

An answer, that will propose to use add() instead of replace() is not welcome.

azizbekian
  • 60,783
  • 13
  • 169
  • 249

2 Answers2

0

I've had RecyclerView declared as a child of NestedScrollView. This was the issue.

When I got rid of NestedScrollView everything was handled automatically.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
-1

As onSaveInstanceState() is not possible, try using ViewModel to save the required data.

When you declare and set the adapter to your first recyclerview, try having a call back to your actvity passing the adapter instance , where in your activity you can try saving the adapter instance or any required data in the ViewModel of your activity.

Once you come back from your details fragment you can get the saved instance of your reycycler data from the activity`s ViewModel.

Pradeep Kumar
  • 102
  • 1
  • 7
  • Why should I save some state of a `Fragment` in the hosting activity? I sure can save scroll position to the `ViewModel` of the fragment, and that can be done in `onDestroyView()`, but my question is how to refrain from this action and make the system save/restore the state automatically. As mentioned in the question, I know about this solution, I'm looking for another solution. – azizbekian Aug 29 '18 at 08:23