Search code examples
androidandroid-architecture-componentsandroid-jetpack

Why is onDestroyView in a fragment called immediately after navigating with JetPack Navigation


Is it normal behaviour that onDestroyView() is called immediately when you navigate to a different fragment?

I call the following method to navigate:

findNavController().navigate(R.id.action_homefragment_to_detailsfragment)

Is there a way to avoid this? Or should everything be restored from a ViewModel? For example my last scroll position in a ScrollView..


Solution

  • Fragments on the back stack have their views destroyed, but the view state is saved and automatically restored when it comes to the top of the stack again (i.e., you hit the system back button).

    Only views with an android:id have their state saved and restored, so make sure any important views have an id.