Created
March 2, 2016 11:06
-
-
Save HugoGresse/c74adef25d76efada4d9 to your computer and use it in GitHub Desktop.
changeFragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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()); | |
} | |
} |
This is great mate, but just a suggestion. If you are using two different instances of the same fragment class, it will not popped up when it should be. The problem is that the tag will be the same for both ( getClass().getName()
). I added String tag
as fourth param.
Thanks indeed.
asante sana
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nicely done, using this right now and its working perfectly well. Thanks again bro