How To Disable both Navigation Bar Back Button and Physical android back button in .Net Maui

How To Disable both Navigation Bar Back Button and Physical android back button in .Net Maui

image.png

I have found that sometimes I need to prevent the user from returning to the home page, in this article I have shown a quick way to implement that using a mainpage and loginpage as an example. The idea is that once a user logs out of an app they should not be able to use the back button on the navigation bar or the physical button that comes with most android phones. Let's see how to do this!

First Step!

  • Add 'NoHistory =true' to your MainActivity.cs ActivityAttribute for Android
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true,NoHistory =true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]

image.png

This is what a page would typically look like after logging out back to the login page

  • On the page that you want to disable the NavigationBar Back Button copy the following override method.

This would go in the XAML code of your page to remove the navigation bar back button. i have used IsEnabled = "False" to disable and "IsVisible"="False" to make it invisible completely to the user.

<Shell.BackButtonBehavior>
        <BackButtonBehavior IsEnabled="False" IsVisible="False"/>
    </Shell.BackButtonBehavior>

This is how it looks to the user, the user can't use the navigation bar to navigate back. Now let's disable the physical button.

image.png

  • Disable the physical back button on Android.

It would be enough to stop at step 2 with iOS but with Android we still have a physical back button. How do we prevent the user from navigating back ? ...this is how.

override the following method in the page you want to disable the back button for.

protected override bool OnBackButtonPressed()
{
   return true;
}

and that's all you need to do, hope this is useful.