I need to override back button.There is OnBackButtonPressed() method but in android is working only for Hardware button! How to override also software navbar button ?
I'm using the same page and I need to back in the previous state of that page (page views are changing by json file change)
Asked
Active
Viewed 498 times
0

xamarinDev
- 95
- 1
- 1
- 11
1 Answers
2
You should go check out Xamarin Help's page about this since it lays out the many reason to fix your design as oppose to implementing something this way (such as displaying a NavigationPage
using PushModalAsync
instead of PushAsync
).
I will also post a link to my other answer on a similar question that talks about another way to handle saving info on a page after the user clicks the back button if they choose to do so.
But the Android gist of the answer from the Xamarin Help site is override OnOptionsItemSelected
in your MainActivity
(if you are not using a MasterDetailPage
in your navigation, you will need to modify the var navPage...
code below):
public override bool OnOptionsItemSelected(IMenuItem item)
{
var app = Application.Current;
if (item.ItemId == 16908332) // This makes me feel dirty.
{
var navPage = ((app.MainPage.Navigation.ModalStack[0] as MasterDetailPage).Detail as NavigationPage);
if (app != null && navPage.Navigation.NavigationStack.Count > 0)
{
int index = navPage.Navigation.NavigationStack.Count - 1;
var currentPage = navPage.Navigation.NavigationStack[index];
var vm = currentPage.BindingContext as ViewModel;
if (vm != null)
{
var answer = vm.OnBackButtonPressed();
if (answer)
return true;
}
}
}
return base.OnOptionsItemSelected(item);
}

hvaughan3
- 10,955
- 5
- 56
- 76