Skip to content Skip to sidebar Skip to footer

How To Keep Fragments In Memory On Orientation Change

I'm creating a tablet optimised application using fragments. I have a thin navigation fragment down the left hand side with buttons to controls what fragments will be loaded into t

Solution 1:

You can't (or really shouldn't) retain fragments in that way. I'm guessing it's state you want to keep.

If you store your state in onSaveInstanceState() you can later retrive it in onCreate() or onActivityCreate(). So after you go back (you'll have to add the FragmentTransaction to the back stack) you can restore the state from the Bundle to which you saved it!

FragmentManager will take care of handling configuration changes and restoring your fragments in their current views.

Solution 2:

I recommend letting android redraw your objects. If you want keep data on orientation change you should keep those in a service component. This way the data will not be lost on orientation change.

otherwise you could always do this:

put this in your manifest

<activityandroid:configChanges="orientation|keyboardHidden"></activity>

put thisin your activity class

@OverridepublicvoidonConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

when using this method your activity will not be redrawn, so your layout will not be adjusted when you are using a seperate XML layout file for either landscape or portrait orientation

Solution 3:

One more thing, you can retrieve the stored Fragment references by FragmentManager#putFragment and FragmentManager#getFragment.

Post a Comment for "How To Keep Fragments In Memory On Orientation Change"