user1755043
user1755043

Reputation: 281

How do I use setRetainInstance (a Fragment method) when I'm using a FragmentActivity?

I want to use setRetainInstance(true) on my FragmentActivity so that onCreate() will not be called every time the screen rotates. I just want to adjust the layout to the screen adjusting without reestablishing my location services connection and notifying the user. How should this be done?

Upvotes: 1

Views: 249

Answers (2)

Martin Marconcini
Martin Marconcini

Reputation: 27236

Start by reading the Fragment documentation about what setRetainInstance does (And does not).

In summary:

public void setRetainInstance (boolean retain)

Added in API level 11 Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:

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.

With that in mind, make sure your "location services connection" and such are located in a place where they will not die (they probably shouldn't be in either Activity or Fragment anyway).

Upvotes: 1

Martin Cazares
Martin Cazares

Reputation: 13705

This paragraph is taken from a book I'm currently reading "Professional Android 4 Application Development"

If an Activity is destroyed and restarted to handle a hardware configuration change, such as the screen orientation changing, you can request that your Fragment instance be retained. By calling setRetainInstance within a Fragment’s onCreate handler, you specify that Fragment’s instance should not be killed and restarted when its associated Activity is re-created.

I think that's clear enough.

Regards!

Upvotes: 1

Related Questions