Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent closing by hardware 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

like image 231
Chris Avatar asked Feb 27 '15 14:02

Chris


3 Answers

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]

like image 90
Chris Avatar answered Oct 12 '22 03:10

Chris


And here's what the code could look like for a Xamarin Forms MasterDetail page scenario...

    public bool DoBack
    {
        get
        {
            MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage;

            if (mainPage != null)
            {    
                bool canDoBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented;

                // we are on a top level page and the Master menu is NOT showing
                if (!canDoBack)
                {
                    // don't exit the app just show the Master menu page
                    mainPage.IsPresented = true;
                    return false; 
                }
                else
                {
                    return true;
                }                    
            }
            return true;
        }
    }
like image 31
Iain STIRZAKER Avatar answered Oct 12 '22 02:10

Iain STIRZAKER


Just give a blank call in the page where do you wanna prevent, like

protected override bool OnBackButtonPressed()
{
return true;
}

This will prevent the back button in XF-Droid.

like image 33
Senthamizh Avatar answered Oct 12 '22 02:10

Senthamizh