Skip to content

Instantly share code, notes, and snippets.

@gabriel-TheCode
Created October 13, 2023 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabriel-TheCode/d9d6f5f6952776f298eb9848f5071f42 to your computer and use it in GitHub Desktop.
Save gabriel-TheCode/d9d6f5f6952776f298eb9848f5071f42 to your computer and use it in GitHub Desktop.
NavigationExtensions
private fun View.goTo(
@IdRes id: Int, bundle: Bundle? = null, navOptions: NavOptions? = null,
navigatorExtras: Navigator.Extras? = null
) {
if (mayNavigate(id)) findNavController().navigate(id, bundle, navOptions, navigatorExtras)
}
private fun Fragment.goTo(
@IdRes id: Int, bundle: Bundle? = null, navOptions: NavOptions? = null,
navigatorExtras: Navigator.Extras? = null
) {
if (mayNavigate(id)) findNavController().navigate(id, bundle, navOptions, navigatorExtras)
}
private fun Fragment.mayNavigate(@IdRes id: Int): Boolean {
val navController = this.findNavController()
val destinationIdInNavController = navController.currentDestination?.id
val destinationIdOfThisFragment = view?.getTag(id) ?: destinationIdInNavController
return if (destinationIdInNavController == destinationIdOfThisFragment) {
view?.setTag(id, destinationIdOfThisFragment)
true
} else {
logDebug { "May not navigate: current destination is not the current fragment." }
false
}
}
private fun View.mayNavigate(@IdRes id: Int): Boolean {
val navController = this.findNavController()
val destinationIdInNavController = navController.currentDestination?.id
val destinationIdOfThisFragment = getTag(id) ?: destinationIdInNavController
return if (destinationIdInNavController == destinationIdOfThisFragment) {
setTag(id, destinationIdOfThisFragment)
true
} else {
logDebug { "May not navigate: current destination is not the current fragment." }
false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment