I am a newbie in xamarin forms app development, currently, I am facing an issue in overriding the toolbar back button onclick. In ios, I am able to achieve but in android its not working can anyone help me out on how to achieve this in my project.
3 Answers
By default it works on iOS and on Android physical back button only. If you want to also support the navigation bar button, you need to use custom platform logic. Take a look on this blog post: Let’s Override Navigation Bar back button click in Xamarin For. He creates a common content page with custom action for back button:
public class CoolContentPage : ContentPage
{
/// <summary>
/// Gets or Sets the Back button click overriden custom action
/// </summary>
public Action CustomBackButtonAction { get; set; }
public static readonly BindableProperty EnableBackButtonOverrideProperty =
BindableProperty.Create(
nameof(EnableBackButtonOverride),
typeof(bool),
typeof(CoolContentPage),
false);
/// <summary>
/// Gets or Sets Custom Back button overriding state
/// </summary>
public bool EnableBackButtonOverride
{
get
{
return (bool)GetValue(EnableBackButtonOverrideProperty);
}
set
{
SetValue(EnableBackButtonOverrideProperty, value);
}
}
}
And then he calls CustomBackAction inside OnOptionsItemSelected method in Anroid code.
Best way to intercept Back Navigation ( Navigation in general ) would be by adding your NavigationPageRenderer so you can control the events and cancel or redirect them, look at my answer How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?
I came to this post with same question about Xamarin forms navigation back button and later discovered that since Xamarin.Forms Shell
this is done easily by overriding the OnNavigating method in the AppShell.xaml.cs
file as I have done here:
protected override void OnNavigating(ShellNavigatingEventArgs e)
{
if(
// Detect Back Navigation
e.Source == ShellNavigationSource.Pop &&
// Make sure it's safe to examine the current page
(Shell.Current != null) &&
(Shell.Current.CurrentPage != null) &&
// Cancel or not, (for example) based on what the Title of the current page is.
(Shell.Current.Title != "My Main Page"))
{
e.Cancel();
Shell.Current.GoToAsync("..");
}
base.OnNavigating(e);
}
In case anyone else stumbles upon, I put a sample on GitHub of what worked for me for Android and iOS both.
Toolbar.NavigationClick += Toolbar_NavigationClick;
in the link? – Robbit