Skip to content

Instantly share code, notes, and snippets.

@Bencodes
Created December 11, 2012 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bencodes/4256282 to your computer and use it in GitHub Desktop.
Save Bencodes/4256282 to your computer and use it in GitHub Desktop.
A function I drag between projects to easily manage Fragments in Android.
public class MyClass extends FragmentActivity {
/**
*
* Simple Fragment management. Lets you easily add Fragments.
*
* @param fragment Fragments to be added on top of the stack
* @param tag The Fragments tag. Can be null.
* @param clearStack If true, it will clear all existing Fragments from the
* stack.
*/
public void addFragment (Fragment fragment, String tag, boolean clearStack) {
final FragmentManager fm = super.getSupportFragmentManager();
final FragmentTransaction transaction = fm.beginTransaction();
if (clearStack) {
for (int x = 0; x < fm.getBackStackEntryCount(); x++) {
fm.popBackStack();
}
}
if (fragment != null) {
transaction.replace(R.id.container, fragment, tag);
if (!clearStack) {
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
transaction.commit();
}
}
public void addFragment (Fragment fragment) {
addFragment(fragment, null, false);
}
public void addFragment (Fragment fragment, String tag) {
addFragment(fragment, tag, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment