You are replacing a fragment that never added before…
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
try
.add(android.R.id.content, new SettingsFragment())
But the right code should be (pseudo code)
- Find fragment by id or tag
- If found fragment is null, then create one.
You can find plenty of examples around the net and stackoverflow. ;)
UPDATE Ok, here's some sample code for you to use as a starting point.
Assumptions: You use the same activity for more than one fragment, so you need to either restore an existing or create a new one.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment newFragment = fm.findFragmentByTag("Some_Tag");
if (newFragment == null) {
newFragment = SomeFragment.newInstance(); //create a new frag
}
// Find the old one to know if we have to replace or simply add to this container
Fragment oldFragment = fm.findFragmentById(R.id.content_container);
if (oldFragment != null) {
ft.replace(R.id.content_container, newFragment, "Some_Tag");
} else {
ft.add(R.id.content_container, newFragment, "Some_Tag");
}
// optionally use a nice transition
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// …and to the backstack if you wish…
ft.addToBackStack(null).commit();
If on the other hand you just want the simple version without anything fancy…
FragmentManager fm = getSupportFragmentManager();//if using support lib
Fragment fragment = fm.findFragmentById(R.id.your_container);
if (fragment == null) {
fragment = YourFragment.newInstance();
fm.beginTransaction()
.add(R.id.your_container, fragment, "some_tag_if_you_wish_to_use_find_by_tag_later")
.commit();
}
This will only add the fragment if the container doesn't have it. Otherwise nothing remains to be done because the container already has your fragment. :)