pop specific fragment from stack and remove others

前端 未结 5 1026
情话喂你
情话喂你 2020-12-30 07:32

how I can pop specific fragment from stack and remove others from a fragment? for example these are my fragments and I\'m in E right know.

A-> B -> C -> D ->E

<
相关标签:
5条回答
  • 2020-12-30 07:55

    You can add a tag to each fragment while adding them to the backstack and then popfragment from backstack till the fragment with the tag you want is not reached.

    FragmentManager fm = getFragmentManager();
    
    for (int i = fm.getBackStackEntryCount() - 1; i > 0; i--) {
        if (!fm.getBackStackEntryAt(i).getName().equalsIgnoreCase(tagname)) {
            fm.popBackStack();
        }
        else
        {
         break;
        }
    }
    
    0 讨论(0)
  • 2020-12-30 07:55

    If you are using AndroidX navigation, you can use the following:

    findNavController().popBackStack(R.id.FragmentB, false)
    
    0 讨论(0)
  • 2020-12-30 08:10

    You can call the function below while you are in Fragment E:

    getFragmentManager().popBackStack("tag", 0);
    

    Here the tag is string passed as tag while adding fragment B to backstack.

    0 讨论(0)
  • 2020-12-30 08:19

    tldr: try using fragmentManager instead of supportFragmentManager if the code doesn't work

    solution: fragmentManager.popBackStackImmediate(tagName, 0)

    I know it's an old question but after spending a few hours on this, I wasn't able to get close to the desired result.

    I was using supportFragmentManager and the code was:

    supportFragmentManager.popBackStackImmediate(tagName, 0)

    but it wasn't working as intended neither according to what was written in the documentation. Just as a fluke I thought about using the fragmentManager instead of the supportFragmentManager and voila, it worked!

    So for anyone stuck on this, maybe give this a try.

    0 讨论(0)
  • 2020-12-30 08:22

    Use following code for pop back stack entry:

     FragmentManager fm = getSupportFragmentManager();
    
        if (fm.getBackStackEntryCount() > 0) {
    
            fm.popBackStack();
    
        }else {
            super.onBackPressed();
        }
    
    0 讨论(0)
提交回复
热议问题