Android back navigation using OnBackPressedDispatcher

In Android 13, the onBackPressed() method was deprecated and replaced by OnBackPressedDispatcher for handling back navigation. This new approach is more flexible and lifecycle-aware, making it ideal for apps with multiple fragments or custom back behavior needs. In this post, we’ll walk through using OnBackPressedDispatcher in activities and fragments to help you manage back navigation effectively.


How to use it?

  1. In your activity/fragment, declare a OnBackPressedCallback variable
  2. Register the callback in onStart() using onBackPressedDispatcher.addCallback(callback)
  3. When user performs the back navigation, handleOnBackPressed() will be called in which you can define your custom logic.
  4. Once you are done listening to back navigation, you can allow the default back navigation by setting isEanble to false.
  5. Remove the callback in onStop() method using remove() function. This is optional as OnBackPressedCallback is lifecycle aware component, but in some cases it is necessary to avoid unexpected behaviour.

1. Example - Saving form when back is pressed

Consider an example where a user has entered data into a form but presses back before saving it. In this case, we can override the back navigation to display a confirmation prompt, ensuring they don’t lose any unsaved data.
  1. Set enableOnBackInvokedCallback to true in AndroidManifest.xml
    
    <application
            ...
            android:enableOnBackInvokedCallback="true"
        
  2. Add few text fiels to your layout file to simulate a form. Here we are creating two fields for name and email.
  3. Open the layout file of your activity/fragment and do the below changes.
    • A OnBackPressedCallback is defines and attached to fragment in onStart() and removed in onDestroyView()
    • By default we disable the back interceptor by setting isEnabled to false so that the default back navigation can happen.
    • A text change lister is added to text fiels and when user inputs the text, the back interceptor is enabled by setting isEnabled to true. When the text fields are blank, we disable the back interceptor.
      
       backPressCallback.isEnabled =
                  !binding.name.text.isNullOrBlank() || !binding.email.text.isNullOrBlank()
          
    • At this point, if user presses the back when form has some data, handleOnBackPressed() is called and a confirmation dialog is shown to save data.
    • If user chooses to cancle saving, we navigate back to previous screen by calling findNavController().popBackStack()
android custom back navigation example

2. Implementing double back press to exit the app

Let's consider another common scenario where the user must press the back button twice to exit the app. This feature is typically implemented to prevent accidental exits. The below example demonstrates how to use the OnBackPressedCallback when having the Navigation Component.
  • Using navigation component destination listener, the back interceptor is enabled only on home screen. Otherwise, the it will be intercepted in child fragments too.
    
        private val navControllerListener =
            NavController.OnDestinationChangedListener { _, destination, _ ->
                // enable back press callback when destination is home fragment
                backPressCallback.isEnabled = destination.id == R.id.HomeFragment
            }
        
  • When the back is pressed, a Toast message is shown asking user to press back again immediately. If user presses the back within 1 sec, the app will be exited. Otherwise the back interceptor in enabled again.
    
    private fun showBackToast() {
            Toast.makeText(this, R.string.press_back_again, Toast.LENGTH_SHORT).show()
            backPressCallback.isEnabled = false
    
            GlobalScope.launch {
                delay(1000)
                // user hasn't pressed back within 1 sec. Enable back press callback again
                backPressCallback.isEnabled = true
            }
        }
        
Here is the full code.
android press back to exit the app
Let me know your queries in the comments section below.

Cheers!
Happy Coding 🤗
Previous Post Next Post

نموذج الاتصال