Search code examples
androidandroid-fragmentsandroid-jetpackandroid-viewmodelandroid-jetpack-navigation

how to save state list in jetpack-navigation


I designed an app using jetpack-navigation There is a problem as illustrated in the following image when I move from one fragment to another one the status of the list disappears.

In fact, when returning from a layout, the article will be re-created in the stack and the list status will not be saved and the user will have to scroll again. Please help me?

jetpack-navigation


Solution

  • The fragment gets recreated on every navigation operation. You could store the scroll position in your activity and load it from there. But doing it like this, the scroll position will be lost on activity recreate (e.g. rotating device).

    Better approch would be to store it in a ViewModel. (see https://developer.android.com/topic/libraries/architecture/viewmodel)

    The view model survives activity recreation and you can store your scroll position.

    Then you can load this position and tell the list to scroll to this position (e.g. for RecyclerView with LinearLayoutManager by calling scrollToPositionWithOffset(...))