Restore the exact RecyclerView scroll state when using BottomNavigationView and NavController

sample list image took from

If you are here looking for a solution to maintain the exact RecyclerView scroll position while navigating between fragments in the BottomNavigationView with setupWithNavController then please continue reading or else good luck with your search 👍

The reason why it does not scroll to the previous position is the navController recreates the fragment (using replace) when used with the bottomNavigation thus losing its state.

I used Activity ViewModel to store the state. If you are using a different approach make sure you store the state in the parent activity or anything which survives longer than the fragment itself.



What are we doing here:

We are storing the layoutManager state in onDestroyView and restore it on onCreateView unlike the scrollToPosition(x) (which is not accurate) this approach will scroll to the exact position when the NavController recreates the fragment.

Happy coding!