Harish_N
Harish_N

Reputation: 2257

How to remove Fragment transactions in middle

I have 5 fragments(say A, B, C, D, E) and one activity with a container. Whenever i want to add a fragment to a container I'll be using the following code.

getSupportFragmentManager().beginTransaction().replace(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();

Let's say i added Fragment A. Upon some action in A, I added fragment B. Upon some action in B, I added fragment C. Upon some action in C, I added fragment D. Upon some action in D, I added fragment E.

Now my stack should be as follows. A -> B -> C -> D -> E

Now upon some action in Fragment E, I need to remove fragments D, C, B so that when user click back, he should directly see Fragment A.

I tried using following code.

public void removeScreen(@NonNull String tag) {
    FragmentManager manager = getSupportFragmentManager();
    Fragment fragment = manager.findFragmentByTag(tag);
    if (fragment != null) {
        FragmentTransaction trans = manager.beginTransaction();
        trans.remove(fragment);
        trans.commitAllowingStateLoss();
    }
}

Upon some action in Fragment E, I called the above function with Tags of Fragment D, C, B(Tags are same as the one that i used for fragment transaction).

Now when i click back button fragment D is becoming visible but i was expecting fragment A.

It would be very helpful if somebody points out where am i going wrong.

Upvotes: 0

Views: 1096

Answers (3)

walker
walker

Reputation: 1

I think your problem occur here :

replace :

getSupportFragmentManager().beginTransaction().replace(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();

to:

getSupportFragmentManager().beginTransaction().add(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();

when you add your fragment to container,tou just add it ,if use"replace" method,you romove it from activirty's fagment manager,it case your "removeScreen" method did not work

Upvotes: 0

romtsn
romtsn

Reputation: 11992

If you want to reach exactly the same behavior that you've described, you can do it by this way:

FragmentManager manager = getSupportFragmentManager();
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

This will clear all backstack until the bottom of stack will be reached.

Upvotes: 1

Sourav Chandra
Sourav Chandra

Reputation: 843

I prefer using DialogFragment for this reason and pop them using interface callbacks and dismiss() function inside them. This is the easiest and quick way to implement what you are trying to do.

Upvotes: 0

Related Questions