Created
September 5, 2018 19:57
-
-
Save mauriciogior/468bdfe64ea9b6272743283f6c59b0d2 to your computer and use it in GitHub Desktop.
Useful helper to handle fragment manager back stack
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
package you.pkg.here; | |
import android.support.v4.app.Fragment; | |
import android.support.v4.app.FragmentManager; | |
/* | |
* Copyright (C) 2018 InEvent, Inc. MIT License | |
*/ | |
public class FragmentManagerHelper { | |
/** | |
* Peeks current back stack without pop. | |
* -- You MUST commit attach fragments with a tag! | |
* @param fragmentManager The support fragment manager v4 | |
* @return Fragment Top fragment at back stack | |
*/ | |
public static Fragment peekBackStack(FragmentManager fragmentManager) { | |
int count = fragmentManager.getBackStackEntryCount(); | |
if (count > 0) { | |
FragmentManager.BackStackEntry topBackStackEntry = | |
fragmentManager.getBackStackEntryAt(count - 1); | |
String tag = topBackStackEntry.getName(); | |
if (tag != null) { | |
return fragmentManager.findFragmentByTag(tag); | |
} | |
} | |
return null; | |
} | |
/** | |
* Commits a new fragment, adds current one to back stack and call `onPause();` on | |
* current fragment. | |
* @param current Current fragment | |
* @param fragmentManager The support fragment manager v4 | |
* @param containerId The id of the container to be used | |
* @param fragment The fragment to be attached | |
* @param tag The fragment's tag | |
*/ | |
public static void pushStackAndPause(Fragment current, FragmentManager fragmentManager, int containerId, Fragment fragment, String tag) { | |
fragmentManager.beginTransaction() | |
.replace(containerId, fragment, tag) | |
.addToBackStack(current.getTag()) | |
.commit(); | |
current.onPause(); | |
} | |
/** | |
* Pops back stack and resume the fragment | |
* @param fragmentManager The support fragment manager v4 | |
*/ | |
public static void popBackStackAndResume(FragmentManager fragmentManager) { | |
Fragment fragment = FragmentManagerHelper.peekBackStack(fragmentManager); | |
fragmentManager.popBackStackImmediate(); | |
if (fragment != null) { | |
fragment.onResume(); | |
} | |
} | |
/** | |
* Pops back stack to specific position, resuming all fragments on each stack count | |
* @param fragmentManager The support fragment manager v4 | |
* @param pos The final position of the stack | |
*/ | |
public static void popBackStackAndResume(FragmentManager fragmentManager, int pos) { | |
while (fragmentManager.getBackStackEntryCount() > pos && fragmentManager.getBackStackEntryCount() > 0) { | |
FragmentManagerHelper.popBackStackAndResume(fragmentManager); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment