Skip to content

Instantly share code, notes, and snippets.

@iscomad
Created March 26, 2021 08:59
Show Gist options
  • Save iscomad/86994ad70db5166f6301a7263fdd28b4 to your computer and use it in GitHub Desktop.
Save iscomad/86994ad70db5166f6301a7263fdd28b4 to your computer and use it in GitHub Desktop.
Helpful FragmentManager extension functions
/**
* 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