【问题标题】:How to prompt for exit when back button is pressed?按下返回按钮时如何提示退出?
【发布时间】:2018-08-11 02:44:51
【问题描述】:

最近我不得不向 Xamarin Forms 移动应用程序添加一项功能。当用户按下后退按钮(在 Android 手机中)时,该功能会显示是/否提示。如果用户选择No,它将丢弃该按钮,否则,它将应用返回按钮,这将隐藏应用程序。

我知道为了检测 Xamarin Forms 中的后退按钮,我必须重写Page.OnBackButtonPressed 方法。对于绕过后退按钮,它应该返回 true,如下所示:

protected override bool OnBackButtonPressed()
{
    if (DisplayAlert("", "Are you sure?", "Yes", "No"))
        return false;

    return true;
}

但问题在于 Page.DisplayAlert 是一个异步方法,必须在主 (UI) 线程上调用。所以经过大量的搜索,我想出了一个我想分享的想法。

我愿意接受有关如何改进的任何想法/建议。

【问题讨论】:

    标签: xamarin.forms async-await xamarin.android back-button


    【解决方案1】:

    我认为答案是在得到 DisplayAlert 的结果后模拟返回按钮。

    为了模拟后退按钮,我发现调用 Activity.OnBackPressed 很有用。

    当然这不是最好的主意,但在 Shared/PCL Xamarin Forms 项目中以这种方式调用此方法很容易:

    1. 在某处(例如页面)定义公共静态 Action 字段
    2. 通过 OnBackPressedMainActivity 类中初始化此字段

    所以整个解决方案是这样的:

    Xamarin 表单页面类

    class MyPage : ContentPage
    {
        public static Action EmulateBackPressed;
    
        private bool AcceptBack;
    
        protected override bool OnBackButtonPressed()
        {
            if (AcceptBack)
                return false;
    
            PromptForExit();
            return true;
        }
    
        private async void PromptForExit()
        {
            if (await DisplayAlert("", "Are you sure to exit?", "Yes", "No"))
            {
                AcceptBack = true;
                EmulateBackPressed();
            }
        }
    }
    

    Xamarin Android MainActivity 类

    public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            MyPage.EmulateBackPressed = OnBackPressed;
    
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
    
            base.OnCreate(bundle);
    
            Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }
    

    【讨论】:

    • App.EmulateBackPressed = OnBackPressed 中的 EmulateBackPressed 引发错误 - 应用程序不包含“EmulateBackPressed”的定义
    • 我已经编辑了答案。只需将 'App.EmulateBackPressed' 替换为 'MyPage.EmulateBackPressed'。谢谢。
    • 现在可以了 :)。你认为它也可以在 iOS 和 Windows 移动设备上运行吗?我无法访问 iOS 模拟器或 Windows 手机,所以不知道..
    • iPhone 没有后退按钮。我不确定 Windows Phone(我猜他们有)。我没有在 Windows Phone 上测试过,但我认为它应该可以工作。
    • 天哪,我忘记了 iPhone 的单按钮。谢谢,您的解决方案非常有用
    猜你喜欢
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多