1

I read on What's onCreate(Bundle savedInstanceState) that onsaveinstancestate gives you a bundle of the previous state of the application(if the orientation of the screen changed.

I looked on the Android docs(http://developer.android.com/training/basics/activity-lifecycle/recreating.html) and saw that you have to manually put the values you want saved as key value pairs. Their code for doing so was

    static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

My question is for fragments, are they automatically reattached when the orientation changes and the activity recreated? Would you have to put code to save it into a bundle? Heres facebook code for this situation that I am trying to understand

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (savedInstanceState == null) {
    // Add the fragment on initial activity setup
    mainFragment = new MainFragment();
    getSupportFragmentManager()
    .beginTransaction()
    .add(android.R.id.content, mainFragment)
    .commit();
} else {
    // Or set the fragment from restored state info
    mainFragment = (MainFragment) getSupportFragmentManager()
    .findFragmentById(android.R.id.content);
}

}

Community
  • 1
  • 1
committedandroider
  • 8,711
  • 14
  • 71
  • 126

1 Answers1

2

To keep a fragment when an Activity gets destroyed, so it automatically reataches, you should call

Fragment.setRetainInstance(true)

in the Fragment's constructor. Nothing is saved by default in onSaveInstanceState()

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158