How to use navigateUp to close the application

As per the navigateUp() documentation and popBackStack() documentation, both return a boolean value indicating:

true if the stack was popped and the user has been navigated to another destination, false otherwise

The NavController only controls its own back stack (i.e., the destinations you’ve put on the back stack) and does not contain or operate on the activity back stack.

If you just want to always finish your activity when the back button is pressed, directly calling requireActivity().finish() is indeed the correct thing to do.

Otherwise, you should be conditionally calling requireActivity().finish() only if popBackStack()/navigateUp() return false – that’s your sign that there’s nothing else on the NavController back stack and you need to handle the back stack yourself.

Leave a Comment