Replacing a Fragment with itself does not show anything

后端 未结 4 719
猫巷女王i
猫巷女王i 2021-01-12 20:19

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 bl

相关标签:
4条回答
  • 2021-01-12 20:45

    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
        }
    }
    
    0 讨论(0)
  • 2021-01-12 20:47

    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.

    0 讨论(0)
  • 2021-01-12 20:50

    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.

    0 讨论(0)
  • 2021-01-12 21:08

    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.

    0 讨论(0)
提交回复
热议问题