Martin
Martin

Reputation: 2266

Android retain View objects in fragment

I have implemented fragment with UI and AsyncTask. For headless Fragment it's recommended use Fragment in combination with the setRetainInstance() method. My question is how to save data on orientation change in this case if Fragment has UI and background process. Thank you for response.

Upvotes: 1

Views: 1182

Answers (1)

Tobrun
Tobrun

Reputation: 18381

When using setRetainInstance(true) the following methods will not be called during orientationChange.

  • onCreate (will only be called when fragment get created)
  • onDestroy (will only be called when activity gets destroyed (e.g. home button etc.)

The other lifecycle will be called e.g.:

  • onCreateView
  • onResume
  • ...

If you want to retain an object, create it in onCreate and handle logic in onDestroy to handle the destroying of the underlying activity. That object will be untouched when orienation occurred. No need to bundle it up or to persist it somewhere locally.

Just a note regarding the title: you don't retain the views themselfs, these should be destroyed and recreated when orientation change occurs. But the object that indicate the state of a view can be retained.

Upvotes: 2

Related Questions