Replacing a Fragment with itself does not show anything

waqaslam picture waqaslam · Feb 19, 2013 · Viewed 7.4k times · Source

I'm trying to decide and show a fragment in activity's onResume method, but in case a previously added fragment is chosen again, then the activity goes blank.

Sample code (with one fragment):

@Override
protected void onResume(){
    FragmentTransaction trans = getSupportFragmentManager().beginTransaction();

    trans.replace(R.id.myLayout, fragA);

    trans.commit();
    getSupportFragmentManager().executePendingTransactions();
}

With above code, when the activity is created for the first time, it shows fragA correctly, but in case I press Home Key and then switch back to my activity (in order to provoke onResume again), it all goes blank (seems like fragA is removed).

Is replacing a previously added fragment removes itself? or how not to loose a fragment if it is replaced by itself?

Answer

Justin Breitfeller picture Justin Breitfeller · Feb 19, 2013

You can't replace a fragment with itself. The first half of a replace is a removal of the previous fragment at that id. Once a fragment is removed it can no longer be added or used by the fragment manager (so the add portion of the replace will not work properly).

Depending on your use case, you have two options:

  1. Create a new fragment instead of reusing the existing instance
  2. Use some other method to see if its necessary to replace your fragment

Finally, you probably don't need to call executePendingTransactions.