I find Fragment#setRetainInstance(true) confusing. Here is the Javadoc, extracted from the Android Developer API:
public void setRetainInstance (boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
- onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
- onCreate(Bundle) will not be called since the fragment is not being re-created.
- onAttach(Activity) and onActivityCreated(Bundle) will still be called.
Question: How do you as a developer use this, and why does it make things easier?
After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity. While Using fragments in the project, the project structure will be good and we can handle it easily.
I became a believer in Fragments in my last application. Whether or not they are computationally faster, they feel faster because you can swap them in and out basically instantaneously, including full support for the back stack if you do it right (call addToBackStack() on the transaction, or something very similar).
How do you as a developer use this
Call setRetainInstance(true)
. I typically do that in onCreateView()
or onActivityCreated()
, where I use it.
and why does it make things easier?
It tends to be simpler than onRetainNonConfigurationInstance()
for handling the retention of data across configuration changes (e.g., rotating the device from portrait to landscape). Non-retained fragments are destroyed and recreated on the configuration change; retained fragments are not. Hence, any data held by those retained fragments is available to the post-configuration-change activity.
It's very helpful in keeping long running resources open such as sockets. Have a UI-less fragment that holds references to bluetooth sockets and you won't have to worry about reconnecting them when the user flips the phone.
It's also handy in keeping references to resources that take a long time to load like bitmaps or server data. Load it once, keep it in a retained fragment, and when the activity is reloaded it's still there and you don't have to rebuild it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With