Replacing a Fragment with itself does not show anything

本秂侑毒 提交于 2019-12-01 04:38:15

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.

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.

waqaslam

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!