Last active
March 13, 2020 23:22
-
-
Save deckyfx/fbf2d2dd6581f5c821c94045b3173b0a to your computer and use it in GitHub Desktop.
Clear BottomNavigation item stack before navigate away
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
// in your activity | |
private fun setupBottomNavigationBar() { | |
val navGraphIds = listOf( | |
..., | |
..., | |
..., | |
..., | |
...) | |
// attach listener to your bottom tab nav view | |
this.extended_bottom_navigation_view?.addOnNavigationItemSelectedListener { | |
// must return boolean, true to proceed tab changes, or false to halt it | |
// depends on your app behaviour, you may want to exclude some tabs | |
when (it.itemId) { | |
... -> { | |
true | |
} | |
else -> { | |
this.clearBackStackBeforeMoveTab(it) | |
} | |
} | |
} | |
} | |
private fun clearBackStackBeforeMoveTab(it: MenuItem): Boolean { | |
// must return boolean, true to proceed tab changes, or false to halt it | |
// try various methods to clean backstack, or set the startDestination / destination to root | |
return if (willBeAbleToBackStack == null) { | |
try { | |
this.currentNavController?.value?.navigate(it.itemId, null, | |
NavOptions.Builder().setPopUpTo(it.itemId, true).build()) | |
true | |
} catch (e: Exception) { | |
e.printStackTrace() | |
true | |
} | |
} else { | |
if (it.itemId == this.currentNavController?.value?.graph?.id) { | |
try { | |
this.currentNavController?.value?.navigate(this.currentNavController?.value?.graph?.startDestination?: 0, null, | |
NavOptions.Builder().setPopUpTo(it.itemId, true).build()) | |
val newPosition = this.activity_post_auth__bottom_navigation_view?.postionForItem(it) | |
if (newPosition != null) this.activity_post_auth__bottom_navigation_view?.checkItem(newPosition) | |
true | |
} catch (e: Exception) { | |
e.printStackTrace() | |
true | |
} | |
} else { | |
this.currentNavController?.value?.navigateUp() != true | |
true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment