4

Is it a good practice to use Fragment.setRetainInstance() for all of your Fragments in order to get rid yourself of handling Fragments recreation, saving instances states, etc? Why not?

Eugene
  • 59,186
  • 91
  • 226
  • 333

2 Answers2

2

Yes, you can use it with fragments not in the back stack if they have to retain configuration changes. It just make things simpler.

See also https://stackoverflow.com/a/8550351/1300995

Community
  • 1
  • 1
biegleux
  • 13,179
  • 11
  • 45
  • 52
  • how can we retain configuration changes in fragments which are maintain in back stack. As we cannot use `setRetainInstance(true)` – Dory Apr 04 '14 at 13:20
2

It's not always good, no. By retaining the instance you are telling 'ye old Android to give you that exact same instance of a Fragment back, i.e. the Fragment's onDestroy is never called rather it is onAttach(ed) and onDetach(ed).

Regularly, you need to re-flow the views to take advantage of a different screen ratio as a result of an orientation change (for example) and having your fragment retaining it's state will mean that the framework will not attempt to use your "landscape friendly" views if started in portrait mode for example.

The affects of onRetainInstance are subtle, it's no silver bullet. Wield with care.

BrantApps
  • 6,362
  • 2
  • 27
  • 60
  • how can we retain configuration changes in fragments which are maintain in back stack. As we cannot use `setRetainInstance(true)` – Dory Apr 04 '14 at 13:22
  • 4
    This is not true, even if you call `setRetainInstance(true)` on your fragment, its `onCreateView()` method will be called again, (and therefore it will be layout again with the new configuration. – nbarraille Aug 07 '15 at 03:50
  • 1
    Just reconfirmed the behaviour and I can see what @nbarraille is referring. Previously when I wrote this answer in 2012 if you had two layouts for a fragment set in onCreateView under different resource qualifiers -port or -land, then by using setRetainInstance(true) would mean that the starting layout would be reused across screen rotations. This does not appear to be the case anymore. Rest assured there were mainly subtle problems with this call previously; http://stackoverflow.com/questions/10456077/nullpointerexception-in-fragmentmanager/ – BrantApps Aug 07 '15 at 12:30