I worked with an issue very similar to this. Since I knew I would frequently be returning back to a previous fragment, I checked to see whether the fragment .isAdded()
was true, and if so, rather than doing a transaction.replace()
I just do a transaction.show()
. This keeps the fragment from being recreated if it's already on the stack - no state saving needed.
Fragment target = <my fragment>;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if(target.isAdded()) {
transaction.show(target);
} else {
transaction.addToBackStack(button_id + "stack_item");
transaction.replace(R.id.page_fragment, target);
}
transaction.commit();
Another thing to keep in mind is that while this preserves the natural order for fragments themselves, you might still need to handle the activity itself being destroyed and recreated on orientation (config) change. To get around this in AndroidManifest.xml for your node:
android:configChanges="orientation|screenSize"
In Android 3.0 and higher, the screenSize
is apparently required.
Good luck