防止 Android 警报对话框在按下中性按钮时关闭

本文关键字:按钮 Android 对话框 防止 | 更新日期: 2023-09-27 18:31:06

我正在使用 Xamarin 和 Nuget 的 V7 支持库。

我想覆盖默认的Dialog.Dismiss()行为。我试过这个没有运气,当按下中性(刷新)按钮时对话框关闭:

为清楚起见,更新:我要求的行为是MyDialog在按下中性按钮后保持打开状态。目前,当按下中性按钮时,refreshMyDialogButton_Click方法会触发,然后MyDialog会自动关闭。

using AlertDialog = Android.Support.V7.App.AlertDialog;
....
protected AlertDialog MyDialog;
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    var myDialogView = View.Inflate(this, Resource.Layout.myDialogView, null);
    MyDialog = createMyDialog(myDialogView);
    MyDialog.Show();
}
protected AlertDialog createMyDialog(View myDialogView)
{
    var builder = new AlertDialog.Builder(this);
    builder
        .SetNegativeButton("back", delegate { MyDialog.Dismiss(); })
        .SetNeutralButton("refresh", (EventHandler<DialogClickEventArgs>)refreshMyDialogButton_Click)
        .SetPositiveButton(/**foo**/)
        .SetView(/**my custom view**/)
        .SetTitle(/**title**/)
        .SetMessage(/**message**/)
        ;
    return builder.Create();
}
private void refreshMyDialogButton_Click(object sender, EventArgs e)
{
    /** start async tasks but don't close dialog **/
}

更新 2

我将以下代码添加到 onCreate 方法中,但这会导致 dialogNeutral 上的空引用异常:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    var myDialogView = View.Inflate(this, Resource.Layout.myDialogView, null);
    MyDialog = createGathererDialog(myDialogView);
    var dialogNeutral = MyDialog.GetButton((int)DialogButtonType.Neutral);
    dialogNeutral.Click += refreshMyDialogButton_Click;
}
protected AlertDialog createMyDialog(View myDialogView)
{
    var builder = new AlertDialog.Builder(this);
    builder
        .SetNegativeButton("back", delegate { MyDialog.Dismiss(); })
        .SetNeutralButton("refresh", (EventHandler<DialogClickEventArgs>)null)
        .SetPositiveButton(/**foo**/)
        .SetView(/**my custom view**/)
        .SetTitle(/**title**/)
        .SetMessage(/**message**/)
        ;
    return builder.Create();
}

防止 Android 警报对话框在按下中性按钮时关闭

按钮必须实例化为 null,然后在调用 .Show() 方法后通过 .GetButton() 进行访问。

我知道我回答这个答案很晚,但你可以在对话类中尝试一下。

this.Dialog.SetCanceledOnTouchOutside(false);

从外面进入时,

dialogBox.Dialog.SetCanceledOnTouchOutside(false);