Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all fragments from container

Is there a way to remove all fragments which are already added the specific view with its view id?

For example I want to remove all fragments which is added into R.id.fragmentcontainer view.

like image 859
Ali Gürelli Avatar asked Oct 20 '15 12:10

Ali Gürelli


People also ask

How do I remove all fragments in the Backstack?

Explanation: MainFragment -> Fragment A -> Fragment B (this is added to backstack) -> Fragment C -> MainFragment (clear backstack ).

How do I remove a fragment from a transaction?

To remove a fragment from the host, call remove() , passing in a fragment instance that was retrieved from the fragment manager through findFragmentById() or findFragmentByTag() . If the fragment's view was previously added to a container, the view is removed from the container at this point.


3 Answers

Its very simple just loop through all the fragments and remove it

for (Fragment fragment : getSupportFragmentManager().getFragments()) {
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}

But in case of Navigation Drawer be sure to check it, if you try to remove it you will get error.

for (Fragment fragment : getSupportFragmentManager().getFragments()) {
  if (fragment instanceof NavigationDrawerFragment) {
      continue;
  }
  else { 
      getSupportFragmentManager().beginTransaction().remove(fragment).commit();
  }
}

Last but very important be sure to check for null before doing any fragment transactions

for (Fragment fragment : getSupportFragmentManager().getFragments()) {
    if (fragment instanceof NavigationDrawerFragment) {
        continue;
    }
    else if (fragment != null) {
        getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }
}
like image 94
Sumit Saxena Avatar answered Oct 18 '22 18:10

Sumit Saxena


In case someone is looking for a code in Kotlin:

supportFragmentManager.apply {
        for (fragment in fragments) {
           beginTransaction().remove(fragment).commit()
        }
        popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    }
like image 12
Devrath Avatar answered Oct 18 '22 18:10

Devrath


It is indeed very simple.

private static void removeAllFragments(FragmentManager fragmentManager) {
    while (fragmentManager.getBackStackEntryCount() > 0) {
        fragmentManager.popBackStackImmediate();
    }
}
like image 8
Jaap-Jan Hellinga Avatar answered Oct 18 '22 17:10

Jaap-Jan Hellinga