等待 Xamarin.Android 的 AlertDialog 用户确认

Await user confirmation for AlertDialog for Xamarin.Android

我需要等待用户确认才能执行某段代码。这是我构建和显示 AlertDialog 的地方:

private bool AskForCommand()
{
    bool userOK = false;
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.SetPositiveButton("Yes", (sender, args) =>
    {
        userOK = true;
    })
    .SetNegativeButton("No", (sender, args) =>
    {
        userOK = false;
    })
    .SetMessage("Send vocal command now?")
    .SetTitle("System Message");
    RunOnUiThread(() =>
    {
        dialog.Show();
    });

    return userOK;
}

这里是我调用方法的地方:

if (!string.IsNullOrEmpty(exactSpeech))
{
    bool userOK = false;
    try
    {
        userOK = AskForCommand();
    }
    catch (Exception ex)
    {
        //TODO: catch
    }

    if (cfg.InstantSendVocal || userOK)
        SendCommandToBoard(exactSpeech);
}

问题是警报显示在方法 "SendCommandToBoard" 之后。

只需将下面的代码放入 SetPositiveButton 回调
dialog.SetPositiveButton("Yes", (sender, args) => { if (cfg.InstantSendVocal) SendCommandToBoard(exactSpeech); }

忘记名为 userOK 的布尔变量