Remove all fragments from container

AndroidAndroid Fragments

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

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

Solution 4 - Android

It is indeed very simple.

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

Solution 5 - Android

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

Solution 6 - Android

Use this code

activity?.let {
it.supportFragmentManager.fragments.forEach { fragment ->
        it.supportFragmentManager.beginTransaction().remove(fragment).commit()
    }
}

Hope it helps.

Thank you.

Solution 7 - Android

Save all your fragments in an ArrayList.

Initializing:

List<Fragment> activeCenterFragments = new ArrayList<Fragment>();

Adding fragment to list:

private void addCenterFragments(Fragment fragment) {
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.empty_center_layout, fragment);
    activeCenterFragments.add(fragment);
    fragmentTransaction.commit();
}

When you want to remove all them, do the following:

private void removeActiveCenterFragments() {
    if (activeCenterFragments.size() > 0) {
        fragmentTransaction = fragmentManager.beginTransaction();
        for (Fragment activeFragment : activeCenterFragments) {
            fragmentTransaction.remove(activeFragment);
        }
        activeCenterFragments.clear();
        fragmentTransaction.commit();
    }
}

I have used this method in production for years, and it works like a charm. Let me know if you have any questions.

Solution 8 - Android

Try this, hope it helps :D

try {
if(manager.getFragments()!=null){
    if(manager.getBackStackEntryCount()>0) {
        for (int i = 0; i < manager.getBackStackEntryCount(); i++)
            manager.popBackStack();

        manager.beginTransaction().remove(getSupportFragmentManager()
        .findFragmentById(R.id.main_content))
        .commit();
        }
    }
}catch (Exception e){
    e.printStackTrace();
} 

Solution 9 - Android

As an addition to useful answers I have to say that if you have added few fragments to specific view container, for example:

getSupportFragmentManager()
	.beginTransaction()
	.add(containerViewId, fragmentA)
	.add(containerViewId, fragmentB)
    .commit();

and if you need just replace them by one, you can simply call replace without removing fragmentA and fragmentB

getSupportFragmentManager()
	.beginTransaction()
	.replace(containerViewId, fragment)
    .commit();

According to the docs replace removes all fragments before adding new:

> Replace an existing fragment that was added to a container. This is > essentially the same as calling remove(Fragment) for all currently > added fragments that were added with the same containerViewId and then > add(int, Fragment, String) with the same arguments given here.

Solution 10 - Android

This Kotlin extension does the job:

fun FragmentManager.removeAll(containerId: Int) {
    beginTransaction().apply {
        fragments.filter {
            it.id == containerId
        }.forEach {
            remove(it)
        }
    }.commit()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaligurView Question on Stackoverflow
Solution 1 - AndroidSumit SaxenaView Answer on Stackoverflow
Solution 2 - AndroidRhn BhadaniView Answer on Stackoverflow
Solution 3 - AndroidDevrathView Answer on Stackoverflow
Solution 4 - AndroidJaap-Jan HellingaView Answer on Stackoverflow
Solution 5 - AndroidVladView Answer on Stackoverflow
Solution 6 - AndroidAjay NishadView Answer on Stackoverflow
Solution 7 - AndroidVingtoftView Answer on Stackoverflow
Solution 8 - AndroidGian_DCView Answer on Stackoverflow
Solution 9 - Androidremain4lifeView Answer on Stackoverflow
Solution 10 - AndroidSemyonView Answer on Stackoverflow