5

Is there any way to know when the 'back' button event on the 'Android phone' is pressed? I'd like to exit the game and add few functionality to it when this button is pressed in Xamarin.Forms. I googled a bit regarding this, but I got articles regarding Xamarin.Android Back button but not for Xamarin.Forms. As I am relatively new to Xamarin.Forms, please help me out

public override void OnBackPressed()
{
    //base.OnBackPressed();
}

Same thing I want in Xamarin.Forms. Need some assistance, guys.

LuizLoyola
  • 386
  • 3
  • 20
adla praveen
  • 161
  • 2
  • 13
  • Possible duplicate of [How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?](http://stackoverflow.com/questions/31696595/how-to-intercept-navigation-bar-back-button-clicked-in-xamarin-forms) – BytesGuy Jul 19 '16 at 10:38
  • You can use OnBackPressed on MainActivity.cs for Android – Dave Rincon Dec 06 '18 at 16:40

2 Answers2

7

If you mean Xamarin.Forms by "Xamarin Cross Platform", there is a OnBackButtonPressed event that you can use. As seen on that documentation:

Event that is raised when the hardware back button is pressed. This event is not raised on iOS.

Simply override this event on your NavigationPage and you're ready to go:

protected override bool OnBackButtonPressed()
{
    // Do your magic here
    return true;
}

Good luck!

MarcoK
  • 6,090
  • 2
  • 28
  • 40
1

In my xamarin forms app you need to find the NavigationStack of the current Page if you are using master page:

public bool DoBack
    {
        get
        {
            MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage;

            if (mainPage != null)
            {    
                bool doBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented;

                //top level of page and the Master menu isn't showing
                if (!doBack)
                {
                    // don't exit the app only show the Master menu page
                    mainPage.IsPresented = true;
                    return false; 
                }
                else
                {
                    return true;
                }                    
            }
            return true;
        }
    }
Himanshu Dwivedi
  • 7,934
  • 3
  • 31
  • 52