Mahdi
Mahdi

Reputation: 6389

pop specific fragment from stack and remove others

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

wanna back from E to B and Clear C and D. How I can do this?

Upvotes: 17

Views: 13361

Answers (5)

Sean
Sean

Reputation: 3025

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

findNavController().popBackStack(R.id.FragmentB, false)

Upvotes: 4

Usman Rafi
Usman Rafi

Reputation: 316

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.

Upvotes: 0

himanshu1496
himanshu1496

Reputation: 1921

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.

Upvotes: 10

Yashoda Bane
Yashoda Bane

Reputation: 399

Use following code for pop back stack entry:

 FragmentManager fm = getSupportFragmentManager();

    if (fm.getBackStackEntryCount() > 0) {

        fm.popBackStack();

    }else {
        super.onBackPressed();
    }

Upvotes: 0

Smit Davda
Smit Davda

Reputation: 638

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;
    }
}

Upvotes: 14

Related Questions