Replacing a Fragment with itself does not show anything

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?


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:

  • Create a new fragment instead of reusing the existing instance
  • Use some other method to see if its necessary to replace your fragment
  • Finally, you probably don't need to call executePendingTransactions.


    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
        }
    }
    
    链接地址: http://www.djcxy.com/p/81410.html

    上一篇: Toast消息不会在x秒内显示在碎片中?

    下一篇: 用自己替换片段不会显示任何内容