本文介绍了防止在Android上的Xamarin表单中通过硬件后退按钮关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在Android上的xamarin表单中按下硬件后退按钮来防止关闭应用程序.

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.

我尝试在 OnSleep 事件中使用xamarin形式,但是在这里我不能取消出口.

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

我还尝试在android中捕获后退按钮:

I also tried catching the back button in android:

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

但是在使用xamarin表单时,我不知道当前正在显示哪个页面.所以我不知道是否允许导航回

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

推荐答案

它与评估NavigationStack(当您使用NavigationPage时)一起使用.

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

在我的活动中,我覆盖了OnBackPressed

In my Activity, I override the OnBackPressed

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

在我的xamarin表单应用程序(App.Instance(单例))中,我将像这样评估当前页面的NavigationStack.

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;
    }
}

当NavigationStack中仅剩一页时,我将不会调用base.OnBackPressed,这样我就不会关闭该应用程序.

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

![测试]

这篇关于防止在Android上的Xamarin表单中通过硬件后退按钮关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:00