Chris Chris - 1 month ago 60
Android Question

Prevent closing by back button in xamarin forms on android

I want to prevent closing the app by pressing the hardware back button in xamarin forms on android.

I want, that you can navigate with the hardware back button in the app (what is working), but do not want to exit, when the first page in navigation stack is reached.

I tried to use the OnSleep event in xamarin forms, but here I can not cancel the exit.

I also tried catching the back button in android:

public override void OnBackPressed()
{
//base.OnBackPressed();
}


But when using xamarin forms, I do not know which page is currently showing. So I do not know if the navigation back is allowed or not

Answer

It works with evaluating the NavigationStack (when you use NavigationPage).

In my Activity, I override the OnBackPressed

public override void OnBackPressed()
{
    if(App.Instance.DoBack)
    {
        base.OnBackPressed();
    }
}

In my xamarin forms app (App.Instance (it is a singleton)), I will evaluate the NavigationStack of the current Page like this.

public bool DoBack
{
    get
    {
        NavigationPage mainPage = MainPage as NavigationPage;
        if (mainPage != null)
        {
            return mainPage.Navigation.NavigationStack.Count > 1;
        }
        return true;                
    }
}

When there is only one page left in the NavigationStack I will not call base.OnBackPressed, so that I will not close the App.

![test]