Reputation: 161
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.
Upvotes: 5
Views: 9698
Reputation: 8174
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;
}
}
Upvotes: 1
Reputation: 6110
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!
Upvotes: 7