I\'m referring to Why use Fragment#setRetainInstance(boolean)?
The reason I ask so is for Activity
to handle rotation, Official Activity Documentation encou
Because you are misunderstanding its use. setRetainInstance(true)
should only be used in fragments that are like solo elements/modules. Fragment that handle sockets etc. an don't have a GUI really benefit from being retained. Fragments with a GUI should probably not use setRetainInstance(true)
. Also any fragments that goes to the backstack shouldn't use setRetainIstance(true)
.
You could generalize it to any fragment which handles only data/connection etc. should use setRetainInstance(true)
. But there is a multitude of different ways to use Fragments, which wouldn't benefit of setRetainInstance(true)
.
Configuration changes: when suddenly screen becomes much wider and much less in height (typical landscape), it is apt for a visual component to update its display and more intelligently use the screen available. Another examples of config change are user sliding the hardware keyboard, device language changing, and so on. why re-start :
Android components favor declarative layout, you load a bunch of XML layouts, and work from there. Finding every View and re-arranging/updating it in real time will be a mess, not to mention the re-wiring of all the event handlers and other custom View code. Its way easier to reload another bunch of layout files.
Also, In Android, Activities kind of live at the mercy of system, so naturally, Activity life cycle is so designed (and recommended) that it is capable of re-creating itself on demand , any time, just as it was before it was destroyed. This pattern accommodates all re-starts, those due to configuration changes as well. If you make your Activities and Fragments capable of maintaining an eternal state, configuration changes won't be that much of a problem.
Retain state data (Models), not the stuff displaying it (UI and Views).
setRetainInstance(true): It is recommended only to be used with fragments that do not hold any reference to anything, that will be recreated on rotation. This means you should not use it on any Fragment that holds Context, Views, etc. A typical Visual fragment does. But it is very useful with Fragments that hold objects like running Threads, AsyncTasks, Data Collections, loaded assets, fetched results etc. This method helps in using a non visual Fragment, as a detachable holder, for non Context-dependent objects of an Activity.