Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Created March 9, 2020 23:29
Show Gist options
  • Save mitchtabian/3d4e58e56a5f07d9ff582f6c275f58a0 to your computer and use it in GitHub Desktop.
Save mitchtabian/3d4e58e56a5f07d9ff582f6c275f58a0 to your computer and use it in GitHub Desktop.
@SuppressLint("RestrictedApi")
fun onBackPressed() {
val navController = fragmentManager.findFragmentById(containerId)!!
.findNavController()
when {
navController.backStack.size > 2 ->{
navController.popBackStack()
}
// Fragment back stack is empty so try to go back on the navigation stack
navigationBackStack.size > 1 -> {
Log.d(TAG, "logInfo: BNC: backstack size > 1")
// Remove last item from back stack
navigationBackStack.removeLast()
// Update the container with new fragment
onNavigationItemSelected()
}
// If the stack has only one and it's not the navigation home we should
// ensure that the application always leave from startDestination
navigationBackStack.last() != appStartDestinationId -> {
Log.d(TAG, "logInfo: BNC: start != current")
navigationBackStack.removeLast()
navigationBackStack.add(0, appStartDestinationId)
onNavigationItemSelected()
}
// Navigation stack is empty, so finish the activity
else -> {
Log.d(TAG, "logInfo: BNC: FINISH")
activity.finish()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment