Remove all fragments from container

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

You can try below code

getSupportFragmentManager().beginTransaction().remove(frag).commit(); 

*frag is the object of fragment that you want to remove.

 OR
getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.your_container)).commit();

it will remove the fragment that is loded in "your_container" container.

HapPy coding.


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

It is indeed very simple.

private static void removeAllFragments(FragmentManager fragmentManager) {
    while (fragmentManager.getBackStackEntryCount() > 0) {
        fragmentManager.popBackStackImmediate();
    }
}

More optimized version
There is no need in multiple call of commit so lets call it one time at the end

supportFragmentManager.fragments.let {
    if (it.isNotEmpty()) {
        supportFragmentManager.beginTransaction().apply {
            for (fragment in it) {
                remove(fragment)
            }
            commit()
        }
    }
}