Reputation: 117
I'm following Advanced android development training by Google. Here is the link. I came across this: Added a static fragment in xml
And on rotating the device, the selected radio button's state is retained as shown here:landscape mode
How is the fragment's state retained without using setRetainInstance(true)? Is the fragment not supposed to be destroyed along with the activity's onDestroy() method? If it is retained without explicitly calling setRetainInstance(true), what's the point of using the method? I'm confused with these two concepts. Can someone shed some light on this?
Upvotes: 2
Views: 94
Reputation: 1006744
How is the fragment's state retained without using setRetainInstance(true)?
Obvious user-mutable state of widgets is usually put into the saved instance state Bundle
automatically. This includes things like the text in an EditText
widget and the checked state of CompoundButton
implementations, such as a RadioButton
.
Is the fragment not supposed to be destroyed along with the activity's onDestroy() method?
Yes.
If it is retained without explicitly calling setRetainInstance(true), what's the point of using the method?
In modern Android app development, you would not use it, preferring to use the ViewModel
system instead. It, under the covers, uses setRetainInstance(true)
.
More generally, the point of retaining a fragment is for retaining state other than the obviously user-mutable state of widgets. For example, you might have some properties referencing business objects (e.g., an invoice, a customer) that you wanted to hold onto across the configuration change.
Upvotes: 2