Skip to content

Instantly share code, notes, and snippets.

@fonix232
Created May 9, 2019 14:45
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 fonix232/78160ff2218a8e52818bef1ebc93a7f1 to your computer and use it in GitHub Desktop.
Save fonix232/78160ff2218a8e52818bef1ebc93a7f1 to your computer and use it in GitHub Desktop.
class NavigationManager {
lateinit var router: Router
var childRouter: Router? = null
//region Generic
fun init(router: Router) {
this.router = router
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(SplashController()))
}
}
fun back(): Boolean {
return router.handleBack()
}
fun restartSplash() {
router.setRoot(RouterTransaction.with(SplashController()))
childRouter = null
}
//endregion
//region BottomNavigationView bits
@IdRes
private var currentSelectedItemId: Int = -1
private var routerStates = SparseArray<Bundle>()
fun initHome(controller: Controller, container: ViewGroup, navbar: BottomNavigationView) {
childRouter = controller.getChildRouter(container)
navbar.setOnNavigationItemSelectedListener { onNavigationItemSelected(it) }
if (routerStates.size() == 0) {
// Select the first item
currentSelectedItemId = R.id.bottombar_one
home_dashboard()
} else {
// We have something in the back stack. Maybe an orientation change happen?
// We can just rebind the current router
childRouter?.rebindIfNeeded()
}
}
private fun onNavigationItemSelected(item: MenuItem): Boolean {
if (currentSelectedItemId == item.itemId) return true
saveStateFromCurrentTab(currentSelectedItemId)
currentSelectedItemId = item.itemId
clearStateFromChildRouter()
val bundleState = tryToRestoreStateFromNewTab(currentSelectedItemId)
if (bundleState is Bundle) {
childRouter?.restoreInstanceState(bundleState)
childRouter?.rebindIfNeeded()
return true
}
when (item.itemId) {
R.id.bottombar_one -> bottombar_one()
R.id.bottombar_two -> bottombar_two()
R.id.bottombar_three -> bottombar_three()
R.id.bottombar_four -> bottombar_four()
else -> return false
}
return true
}
private fun clearStateFromChildRouter() {
childRouter?.apply {
setPopsLastView(true) /* Ensure the last view can be removed while we do this */
popToRoot()
popCurrentController()
setPopsLastView(false)
}
}
private fun saveStateFromCurrentTab(itemId: Int) {
val routerBundle = Bundle()
childRouter?.saveInstanceState(routerBundle)
routerStates.put(itemId, routerBundle)
}
[ bottombar_one() ... bottombar_four() implementations, calling childRouter?.setRoot() with the appropriate subpage controller
//endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment