arjun
arjun

Reputation: 3574

setRetainInstance(boolean) method in fragments

Its known from docs that setRetainInstance(boolean) method helps retains all active objects across device configuration changes, but most of the examples and documentations I read deals with headless fragments. Should we not use that method in fragments with UI elements. If not could any please give a detailed reason.

Upvotes: 1

Views: 81

Answers (1)

Emanuel Moecklin
Emanuel Moecklin

Reputation: 28856

Don't use headless fragments for background processing. Even if articles like this one: http://www.vogella.com/tutorials/AndroidFragments/article.html#headlessfragments1 or this one: http://luboganev.github.io/blog/headless-fragments/ mention it.

Background processing should be done in a Service (alternatives exist but the question isn't about that). That's the component meant to do background processing while doing it in a headless fragment is a "loophole" (not the way Google meant fragments to be used).

Note: some devices don't retain the Fragment across a configuration change even with setRetainInstance(true). Using a headless fragment to run background tasks would obviously not work well on those devices.

setRetainInstance(true) is meant to be used with Fragments that have a ui to retain it across a configuration change. Very convenient if you use Loaders in a Fragment since the (expensive?) query won't re-run even if the Activity is destroyed and re-created.

Upvotes: 2

Related Questions