Handle Back Button in Xamarin Forms for Android
How to dynamically handle Back Button on Android Devices for any Screen
After a great article from Dylan Berry about Confirm Exit from Android application with Xamarin Forms, I start thinking why can’t we do this on every screen we want?
This solution prepared for Xamarin.Forms with MvvmCross v6.4.* Framework. I would like to pay attention here to that because not all search for a solution with MvvmCross Framework. If you are interested, I can write a blog post with other Mvvm Frameworks such as Prism or other 😉
Let me introduce to you our way to handle Back Button Pressed on Android devices. First of all, we need to define an interface by which we will check and handle the back button pressed:
Quite simple — right 😅, let’s move on. Next step in our preparation is a
OnBackPressed handler at our
And, that’s it. Tada 🥁🤩.
You may ask me why I used reflection here? — I’m also not a big fan of reflection and in Xamarin.Android (mean “Native”) you can do it without reflection at all. In Xamarin.Android we can manually set
Fragment Id at xml(axml) layout file and get it by
But Xamarin.Forms team made his
FragmentContainer, which has a property
Page , is
internal and we can’t easily access that:
That’s why we should use a little bit of reflection at Xamarin Forms 😯, but don’t worry, very very little 😋.
Implementation of IBackButtonHandler in ViewModel
The last thing — is an implementation of
IBackButtonHandler in our ViewModels where we want to control the pressing of the back button on Device. It’s again quite simple:
Here I show typical Logout Confirmation Dialog from “Home” Screen when user press Back Button, but it’s could be used in the same way as in blog from Dylan Berry or in any other Screen where we have unsaved data or something similar.
Hmm, what can I say here 🤔, there are a lot of ways to control back button pressed or confirm exit action from an application and each of them could be useful in specific scenarios. I hope some of you will be happy to use the proposed solution 🥰.
Just let me know about your ways. About this article at all. And let me know if you are interested to have the same article with Prism or other Mvvm Frameworks 🙂.
Cheers folks 😎