How To Confirm Exit in Android with Xamarin Forms

Update – 2020-03-05 I updated the samples and snippets to include some reader feedback: Accounted for Master-Detail navigation in App.PromptToConfirmExit Provided a toast + back button confirmation alternative sample Updated sample: allow toggling between Master-Detail and Tabbed navigation; allow toggling between dialog and toast confirmation styles. Overview Ever hit the navigation bar back button when […]

Update – 2020-03-05

I updated the samples and snippets to include some reader feedback:

  1. Accounted for Master-Detail navigation in App.PromptToConfirmExit
  2. Provided a toast + back button confirmation alternative sample
  3. Updated sample: allow toggling between Master-Detail and Tabbed navigation; allow toggling between dialog and toast confirmation styles.

Overview

Ever hit the navigation bar back button when using an Android app and have it fully exit the app and drop you back on your home screen? I think all Android users have encountered this a few times. It is a frustrating and counter-productive experience. Let’s make sure your app has better UX by using a simple confirmation dialog!

Xamarin Forms Android Exit Confirmation

Good news, this is easy to implement and should only take you a few minutes to code and test.

Step 1

Create a property to check if there are pages on your navigation stack. Here’s my implementation:

Step 2

Override the OnBackPressed method in your app’s MainActivity to intercept back navigation. Here’s a sample:

We’re Done!

Wasn’t that easy! Let me know how this works out for your app. Check out my full Xamarin Forms Android Exit Confirmation sample on Github.