falsetto
falsetto

Reputation: 789

Properly replacing Fragments

I'm wondering which is the proper way to change Fragments, add them to backstack, and restore the visibile Fragment after a screen rotation.
Currently, I use this method to initialize the first Fragment:

private void inflateInitialFragment() {
    FragmentManager manager = getFragmentManager();
    Fragment mainFragment = manager.findFragmentByTag(MainMenuFragment.class.getSimpleName());
    FragmentTransaction ft = manager.beginTransaction();
    if (mainFragment == null) {
      ft.replace(R.id.mainContainer, new MainMenuFragment(), MainMenuFragment.class.getSimpleName());
    } else if (!(mainFragment.isAdded() && !mainFragment.isDetached() && !mainFragment.isRemoving())) {
      ft.replace(R.id.mainContainer, mainFragment, MainMenuFragment.class.getSimpleName());
    }
    ft.commit();
    manager.executePendingTransactions();
}

And then to display new Fragments I have methods like this one:

public void openAwards() {
   getFragmentManager().beginTransaction().replace(R.id.mainContainer,
    new AwardsFragment(), AwardsFragment.class.getSimpleName()).addToBackStack(null).commit();
}

And to go back to the main screen:

@Override
public void onBackPressed() {
   if (getFragmentManager().getBackStackEntryCount() == 0) {
      super.onBackPressed();
   } else {
      getFragmentManager().popBackStack();
   }
}

After a few screen rotations, I've got crashes like this one:

java.lang.IllegalStateException: Fragment already added: MainMenuFragment{42c64d90 #0 id=0x7f0b003f MainMenuFragment}

How should I change the visible Fragments and restore them after a screen rotation?
I don't think that saving some string or Fragment each time is a good solution to restore them.

Upvotes: 2

Views: 70

Answers (1)

czajna666
czajna666

Reputation: 597

If your Activity extends android.app.Activity you don't need to override onBackPressed(). It will pop your fragments from back stack automatically.

Upvotes: 1

Related Questions