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.
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:
Android : You'll need to override the OnOptionsItemSelected () event in our MainActivity class in order to capture the nav bar back button click in Android for Xamarin Forms.
For more information, see Pressing and releasing the button in the Xamarin.Forms Button guide. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator.
Xamarin.Forms Shell introduced route based navigation to Xamarin.Forms applications to easily navigate through applications and also pass data through query properties. Sometimes in your application it is not always about navigating forward to pages, but it is about navigating backwards when your users perform an action.
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!
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With