Junior — Middle
How is the lifecycle of a fragment managed in Android when the device configuration changes?
sobes.tech AI
Answer from AI
When the device configuration changes (for example, screen rotation), the activity and its fragments are by default destroyed and recreated. The fragment's lifecycle then goes through the following stages:
- onPause() → onStop() → onDestroyView() → onDestroy() → onDetach() — the fragment is destroyed along with the activity.
- After the activity is recreated, a new instance of the fragment is created, and the methods onAttach() → onCreate() → onCreateView() → onActivityCreated() → onStart() → onResume() are called.
To preserve the fragment's state during configuration changes, you can use the onSaveInstanceState() method to save data and restore it in onCreate() or onViewCreated(). You can also use setRetainInstance(true) to retain the fragment itself during activity recreation, but this method is deprecated and not recommended.
For more flexible management, ViewModel is often used, which survives configuration changes and stores data separately from the fragment's lifecycle.