FragmantClass rSum = new FragmantClass();
getSupportFragmentManager().beginTransaction().remove(rSum).commit();
I am trying to remove this fragm
This is a very straightforward solution for SupportFragmentManager
. FragmentManager
isn't quite as convenient, but still effective:
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
// You might have to access all the fragments by their tag,
// in which case just follow the line below to remove the fragment
if (fragmentList == null) {
// code that handles no existing fragments
}
for (Fragment frag : fragmentList )
{
// To save any of the fragments, add this check
// a tag can be added as a third parameter to the fragment when you commit it
if (frag.getTag().equals("<tag-name")) {
continue;
}
getSupportFragmentManager().beginTransaction().remove(frag).commit();
}
or, if you're forced to use it (but not recommended):
.commitAllowingStateLoss();
If you're removing all fragments from the view multiple times, you might consider checking if the current frag is null or isDetached()
or isRemoving()
or you might get a NullPointerExceptions
.
Update 6-9-15: The documentation for getSupportFragmentManger().getFragments()
is apparently hidden now, but still works just fine in my code. Here's the screenshot of the documentation:
Update 8-3-15: If you're not using the support library for fragments, there is unfortunately no getFragments()
available, but there are still a couple, more inconvenient, options.
fragment
a tag
or id
upon creation, and iterate through them to process each fragment
as desired.onAttachListener
so each time a new fragment
is attached to the activity
, you can store that fragment
, and then iterate through that data structure to process each fragment
as desired.When not using the getSupportFragmentManager()
, to process a transaction you will need to use getFragmentManager()
instead.
More simple, you can replace the main content with an empty fragment, so that the main activity is viewed only.
getFragmentManager()
.beginTransaction()
.replace(main_content,new Fragment())
.commit();
In my personal case, I add and remove fragment this way:
if(getSupportFragmentManager().findFragmentById(R.id.container) != null) {
getSupportFragmentManager()
.beginTransaction().
remove(getSupportFragmentManager().findFragmentById(R.id.container)).commit();
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.commit();
getSupportFragmentManager().beginTransaction().
remove(getSupportFragmentManager().findFragmentById(R.id.frame)).commit();
Try this, it should work.
public void switchContent(Fragment fragment) {
getSupportFragmentManager().beginTransaction().
remove(getSupportFragmentManager().findFragmentById(R.id.frame)).commit();
mContent = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
getSlidingMenu().showContent();
}