3

I have a fragment, which I add with a tag like this:

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,fragment,fragment_tag).commit();

At some point, in another fragment, I need to remove this fragment so I call:

fragment = getActivity().getSupportFragmentManager().findFragmentByTag(fragment_tag);
if(fragment != null && fragment.isAdded())
    fragmentManager.beginTransaction().remove(fragment).commit();

In theory, the next time I call findFragmentByTag() for the fragment I just removed, I should get a null, however, the next time i call this:

fragment = getActivity().getSupportFragmentManager().findFragmentByTag(fragment_tag);
if(fragment != null)

The if statement is true so it actually finds a fragment with that tag!

My question is, how do I COMPLETELY remove a fragment?

Take in consideration that the fragment to be removed may not be in the top of the backstack, that meaning that popBackStack() is not a solution.

Ricardo
  • 9,136
  • 3
  • 29
  • 35

2 Answers2

0

After you remove the fragment, it might still be in the fragment manager back stack, so to completely remove it you have to remove if from the fragment manager back stack, so you have to pop it out of the back stack by calling the fragmentManager.popBackStack(String, int) method...

Check out the method Fragment Manager pop back stack method

oziomajnr
  • 1,671
  • 1
  • 15
  • 39
  • Thanks for your attention. Check my edited question. The fragment may not be in the top of the backstack – Ricardo Jul 13 '17 at 14:26
  • did you try it? if you want it removed immediately you can call popackStackImmeditely(); – oziomajnr Jul 13 '17 at 15:00
  • I did try that. And i have searched over SOF which present this solution but that does not help my case – Ricardo Jul 13 '17 at 15:15
  • and the fragment was not declared in the activity layout file? – oziomajnr Jul 13 '17 at 15:35
  • Let's say I have 5 fragments, which are added to the activity, the fragment I intend to remove is not in the top of the backstack. All of them are added in the activity, each one with its own tag – Ricardo Jul 13 '17 at 15:58
  • @Ricardo Did you solve this problem ? I'm facing the same one. – Bulma May 17 '19 at 13:19
-1
int index = getSupportFragmentManager().getFragments().indexOf(oldfragment);
        getSupportFragmentManager().getFragments().set(index, null);
Amine Jallouli
  • 3,919
  • 8
  • 36
  • 73
Amit kumar
  • 149
  • 14