0

In my app I'm using the Jetpack navigation component and I have an issue with fragment state not being saved when navigating back to a fragment.

When I navigate from MainFragment to SettingsFragment it's via the overflow menu: NavigationUI.onNavDestinationSelected(item, Navigation.findNavController(view));

When navigating back to MainFragment, the visibility on some views and text in some TextViews is not saved, and my state machine variable has lost its state as well.

I've read solutions where the root view is saved in a global variable in the fragment, and while this solves the visibility issue on views, the TextViews are still empty and the state machine variable is reset.

Is there a proper way to make sure fragment state is saved in this case?

Eric B.
  • 673
  • 11
  • 16
  • Does your Fragment also lose state when you rotate your device? What about when you enable 'Don't keep activities'? If so, you're already losing state and you should fix that first. – ianhanniballake Nov 12 '19 at 01:35
  • @EricB , it seems that is expected behavior of Navigation, you can [read this discuss and try the solution](https://stackoverflow.com/questions/54581071/fragments-destroyed-recreated-with-jetpacks-android-navigation-components) – NamNH Nov 12 '19 at 02:18
  • You should really just save your state properly. – ianhanniballake Nov 12 '19 at 02:44
  • @ianhanniballake that's basically my question, how to save instance state. How do you recommend I do that when `OnSaveInstanceState()` isn't called? And views that have IDs should save state, correct? – Eric B. Nov 12 '19 at 05:06

1 Answers1

1

If you're using view model then it can save state for you. However, that only works for simple views. For complex views including some custom views that you created, make sure that you have assigned a unique id to those as Android uses those ids to recover their state. You can use generateViewId() method on View to do so. Worst case, you might need to implement onSavedInstanceState and onRestoreInstanceState on your views.

Also, make sure you have not set to setRetainInstance to false in the xml or code.

While doing that please make sure you use parcelize annotation for your parcelable data models as this can save you a lot of time.

I hope your problem is solved by assigning unique IDs and you don't have to deal with saving state. Good luck!

ked
  • 79
  • 5
  • Lots of good info here, thanks! I don't have custom views and all my views have IDs, so I think you're right with using a ViewModel. I'm not currently using that but will give it a shot. – Eric B. Nov 20 '19 at 07:05