Reputation: 12666
Calling Fragment.setRetainInstance(true)
will cause the Fragment
to be retained by the FragmentManager
, but is it's View
retained? I think not, but I'm looking for confirmation. I think not because Fragment.onCreateView()
is still called (even though onCreate()
isn't) and calling getView()
returns null
.
What is the point of retaining a Fragment
across configuration changes if its View
s aren't? One reason is to retain data, to avoid expensive reloads, but there are other ways to do that.
Thanks in advance...
Upvotes: 5
Views: 1428
Reputation: 1007296
Does a retained Fragment retain its View?
That depends on how you define it. The fragment will have onCreateView()
called again, and so it is supposed to set up its UI for the new activity. However, if you have field holding onto widgets, those fields are retained, and it is your job to have those fields point to the new widgets, to avoid memory leaks and other problems.
What is the point of retaining a Fragment across configuration changes if its Views aren't?
To retain data, to avoid expensive reloads.
but there are other ways to do that
Only with limits.
For example, all else being equal, it is better to retain data via the saved instance state Bundle
. However, that Bundle
cannot hold onto arbitrary objects (e.g., a Camera
), and there is a ~1MB limit on the size of the Bundle
, so it cannot hold onto large objects (e.g., a photo).
Part of the reason for the term "retain" is that retained fragments build atop the old onRetainNonConfigurationInstance()
callback on Activity
. That is now final
and cannot be used, IIRC.
Data whose life is broader than the current activity can be cached globally (e.g., POJO cache for database/network I/O results, image cache). However, some things, like a Camera
, do not belong in static data members like that.
Stuff you retrieve using the Loader
framework (e.g., via CursorLoader
) is automatically retained, but the Loader
framework has its own issues for things other than CursorLoader
.
You don't have to use a retained fragment. I find them reasonably useful.
Upvotes: 6
Reputation: 2611
I usually use setRetainInstance
on non-UI fragments (that do not implement onCreateView
). I delegate lengthy operations (api calls on a server for example) so that they still happen during a configuration change (screen rotation) and when my UI comes back up I can just connect back to the retained fragment for the result/progress.
Upvotes: 0