Junior — Middle
How does Fragment behave when the configuration changes if the setRetainInstance(true) command is called?
sobes.tech AI
Answer from AI
If the setRetainInstance(true) command is called in a Fragment, then when the configuration changes (for example, screen rotation), the fragment instance itself is not destroyed or recreated. This allows preserving the fragment's state and data without re-initialization.
Behavior features:
- The fragment is retained and reused after the Activity is recreated.
- Fields and objects inside the fragment are preserved, which is convenient for long operations (e.g., data loading).
- However, the fragment's view will still be recreated, so references to the view need to be updated in lifecycle methods (e.g., in
onCreateView).
Important: starting from newer versions of Android, using setRetainInstance(true) is considered deprecated, and other approaches for saving state, such as ViewModel, are recommended.