Created
March 26, 2021 08:59
-
-
Save iscomad/86994ad70db5166f6301a7263fdd28b4 to your computer and use it in GitHub Desktop.
Helpful FragmentManager extension functions
This file contains hidden or 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
/** | |
* Invokes func body in a fragment transaction | |
* | |
* @allowStateLoss - a flag which determines whether to use #commitAllowingStateLoss or #commit. See {@link FragmentTransaction#commitAllowingStateLoss} | |
* @func - a body which is invoked inside a fragment transaction | |
*/ | |
inline fun FragmentManager.inTransaction( | |
allowStateLoss: Boolean = false, | |
func: FragmentTransaction.() -> Unit | |
) { | |
val transaction = beginTransaction() | |
transaction.func() | |
if (allowStateLoss) { | |
transaction.commitAllowingStateLoss() | |
} else { | |
transaction.commit() | |
} | |
} | |
/** | |
* Returns the top fragment of the current FragmentManager | |
* | |
* @return - a Fragment that is located on top of the FragmentManager | |
*/ | |
fun FragmentManager.getCurrentFragment(): Fragment? { | |
var fragmentTag: String? = "" | |
if (backStackEntryCount > 0) | |
fragmentTag = getBackStackEntryAt(backStackEntryCount - 1).name | |
return findFragmentByTag(fragmentTag) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment