c# - Android AlertDialog,不要在按键时关闭,而是在触摸时关闭

标签 c# android xamarin android-alertdialog

我找到了在触摸对话框按钮或按下键盘上的按键时取消消除 AlertDialog 的解决方案。但是,我只想在按下时取消关闭,触摸按钮应该仍然有效。

例如,如果按下某个键,如何保持 AlertDialog 打开,但保持按钮触摸功能?

由于我使用的是 Xamarin,所以到目前为止,这是我的 C# 代码,但真正的 Java 解决方案也被接受,因为它们很容易翻译:

构建对话框:

AlertDialog dialog = new AlertDialog.Builder(this)
    .SetTitle("blabla")
    .SetMessage("more bla")
    .SetPositiveButton("OK", (sender2, e2) => {
        // Do something
        SetResult(Result.Ok, oIntent);
        Finish(); })
    .SetNegativeButton("Cancel", (sender2, e2) => { })
    .Create();
dialog.SetOnShowListener(new AlertDialogShowListener(dialog));
dialog.Show();

以及接口(interface)的实现:

private class AlertDialogShowListener : Java.Lang.Object, IDialogInterfaceOnShowListener {
    private AlertDialog _dialog;

    internal AlertDialogShowListener(AlertDialog dialog) {
        _dialog = dialog;
    }

    public void OnShow(IDialogInterface dialog) {
        Button b = dialog.GetButton((int)DialogButtonType.Positive);
        b.SetOnClickListener(new ButtonOnClickListener());
        b = dialog.GetButton((int)DialogButtonType.Negative);
        b.SetOnClickListener(new ButtonOnClickListener());
    }
}

private class ButtonOnClickListener : Java.Lang.Object, View.IOnClickListener {
    public void OnClick(View v) {
        // How to NOT dismiss if a _key_ has been pressed?
    }
}

(PS:我知道在 Xamarin 中通过附加 Click 事件编写这样的代码有一种更简单的方法,但我认为 Java 专业人员使用 OnShow 和 OnClick 监听器更容易遵循这种方式。)

最佳答案

我找到了答案!

显示警报对话框后,获取按钮并重写其 onKeyPress 方法,这样这些按钮就不会在警报对话框上调用关闭。

在 C# 中,它看起来像这样:

AlertDialog dialog = new AlertDialog.Builder(this)
    .SetTitle("blabla")
    .SetMessage("blablabla")
    .SetPositiveButton("OK", (sender, e) => {
        SetResult(Result.Ok, oIntent);
        Finish();
    })
    .SetNegativeButton("Cancel", (sender, e) => { })
    .Show(); // Important, or GetButton() will return null

// Now disable the default dismissing actions on key presses.
dialog.GetButton((int)DialogButtonType.Positive).KeyPress += (sender, e) => { };
dialog.GetButton((int)DialogButtonType.Negative).KeyPress += (sender, e) => { };

关于c# - Android AlertDialog,不要在按键时关闭,而是在触摸时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25844373/

相关文章:

c# - 如何允许用户输入 Value1 然后说 Value1 = Value2

c# - Winform 出现 Red X 异常

ios - Xamarin.iOS CoreBluetooth/外部附件问题

c# - Xamarin 如何通过单击新资源布局来打开另一个布局

C# 检查我是否理解正确的赋值

c# - 如何存储/检索大量用户身份声明

android - AsyncTask 第一次执行时花费太多时间

java - 使用 Retrofit 2 下载文件时内存不足

java - 随着 map 的移动在谷歌地图上获取标记

visual-studio - Xamarin跨平台(可移植类)项目编译错误