Skip to content

Instantly share code, notes, and snippets.

@HugoGresse
Created March 2, 2016 11:06
Show Gist options
  • Save HugoGresse/c74adef25d76efada4d9 to your computer and use it in GitHub Desktop.
Save HugoGresse/c74adef25d76efada4d9 to your computer and use it in GitHub Desktop.
changeFragment
/**
* Change the current displayed fragment by a new one.
* - if the fragment is in backstack, it will pop it
* - if the fragment is already displayed (trying to change the fragment with the same), it will not do anything
*
* @param frag the new fragment to display
* @param saveInBackstack if we want the fragment to be in backstack
* @param animate if we want a nice animation or not
*/
private void changeFragment(Fragment frag, boolean saveInBackstack, boolean animate) {
String backStateName = ((Object) frag).getClass().getName();
try {
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
//fragment not in back stack, create it.
FragmentTransaction transaction = manager.beginTransaction();
if (animate) {
Log.d(TAG, "Change Fragment: animate");
transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
}
transaction.replace(R.id.fragment_container, frag, backStateName);
if (saveInBackstack) {
Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
transaction.addToBackStack(backStateName);
} else {
Log.d(TAG, "Change Fragment: NO addToBackTack");
}
transaction.commit();
} else {
// custom effect if fragment is already instanciated
}
} catch (IllegalStateException exception) {
Log.w(TAG, "Unable to commit fragment, could be activity as been killed in background. " + exception.toString());
}
}
@nickyrabit
Copy link

asante sana

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment