9

I have a Fragment stack like this

F1 -> F2 -> F3 -> F4 -> F5

Now I need to remove F2, F3, F4 fragments.

I need if i press back button from F5 fragment, it should be go to F1.

NOTE: I am not changing fragment fragment from activity. changing fragment from fragment.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
AvisSiva
  • 707
  • 1
  • 9
  • 17
  • Possible duplicate of [Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?](https://stackoverflow.com/questions/5802141/is-this-the-right-way-to-clean-up-fragment-back-stack-when-leaving-a-deeply-nest) – Vadim Kotov Jun 21 '19 at 16:24

3 Answers3

11

On destroy of the Fragment F5 clear Back Stack upto F2.

Try something like this:

public method in your MainActivity:

public void clearBackStackInclusive(String tag) {
     getSupportFragmentManager().popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

now in your F5 fragment:

@Override
public void onDestroy() {
   super.onDestroy();
   ((MainActivity)getActivity()).clearBackStackInclusive("tag"); // tag (addToBackStack tag) should be the same which was used while transacting the F2 fragment
}

Reference

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
2

You can manage tasks with flags. For example, this will clear all the activities on top of home.

Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent)

So if you start 4 or 5 or more tasks over the Home Activity, you can call finish on the fifth and get back home.

I am looking forward for a fragment version of it, but it depends on the way you manage tasks.

EDIT

I found it for fragments :

FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27
0

Well you can achieve this behavior, using F1 to manage every think. Supposing that you are doing an process were every step depends on the last answer. all you got to do is come back to F1 every answer you got than make F1 open the next step. For example:
1° In F1 you say that you what to show an person phone number
2° F1 call F2 were you search an name. When user select an name F2 returns to F1 the name and closes
3° F1 gets the name than F2 returned and call F3 with this name and F3 shows the number

Not really fancy, but at least worked for me when i had to do something similar.