Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setRetainInstance(true) in onCreate fragment in android

I am not holding any context in my fragment so I am using setRetainInstance(true) in UI fragment. can any one tell me whether this is the correct approach? Also where we should basically call setRetainInstance method? I mean in onCreate or onActivityCreated etc.

like image 694
doubt Avatar asked Jan 21 '26 09:01

doubt


1 Answers

Introduction: setRetainInstance(boolean)

When you look at the Reference, you see:

  • 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.

Then, where do I should use this method?

This method is used to retain a fragment when the configuration change. You need to set this method in fragment at its first creation. When you see above that onAttach or onActivityCreated will still be called after a rotation, don't set the method inside because you will called it again. It's useless...! The best approach is to call setRetainInstance inside onCreate method, because this last will not be called again after a changing rotation.

What's the correct approach to use it?

All depends what you want and do with your FragmentActivity and fragments. I'll answer with a quote by Alex Lockwood:

Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread or AsyncTask, managing its operation. See my blog post on this topic for more information.

In general, I would treat it similarly to using onConfigurationChanged with an Activity... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.

like image 57
Blo Avatar answered Jan 23 '26 21:01

Blo