Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You can try:

if( !(getSupportFragmentManager().findFragmentById(R.id.myLayout) instanceof FragmentA) ) {
    FragmentTransaction trans = getSupportFragmentManager().beginTransaction();

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

    trans.commit();
}

And I assume that fragA is FragmentA class object.

Finally, I had to put a check before replacing fragments. In case, an (already added) fragment is requested for replace again, I had to check if its already added then ignore the replacement, else proceed. For example:

@Override
protected void onResume() {
    if (!fragA.isAdded()) {
        FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
        trans.replace(R.id.myLayout, fragA);
        trans.commit();
        //getSupportFragmentManager().executePendingTransactions();   //unnecessary
    }
}

When referencing back to a created Fragment please do make sure to try adding the

fragmentTransaction.addToBackStack(null); 

method right before committing so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.

You can find this at the end of this page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top