Is there a way to remove all fragments which already added the specific view with its view id?
For example I want to remove all fragments which is added R.id.fragmentcon
Use this code
activity?.let {
it.supportFragmentManager.fragments.forEach { fragment ->
it.supportFragmentManager.beginTransaction().remove(fragment).commit()
}
}
Hope it helps.
Thank you.
In case someone is looking for a code in Kotlin:
private fun clearFragmentsFromContainer() {
val fragments = supportFragmentManager.fragments
if (fragments != null) {
for (fragment in fragments) {
supportFragmentManager.beginTransaction().remove(fragment).commit()
}
}
//Remove all the previous fragments in back stack
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
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()
}
}
}
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();
}
It is indeed very simple.
private static void removeAllFragments(FragmentManager fragmentManager) {
while (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStackImmediate();
}
}
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.