Search code examples
androidandroid-recyclerviewandroid-viewandroid-scrollviewandroid-savedstate

Restore RecyclerView's scroll position after performing Fragment replace()


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.


Solution

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

    When I got rid of NestedScrollView everything was handled automatically.