如何在AlertDialog(Xamarin.Android)中触发事件?

时间:2018-01-12 08:43:30

标签: events xamarin.android call

我创建了以下AlertDialog:

Dialog dialogConfirmTransfer = new Dialog(this);
AlertDialog.Builder alertConfirmTransfer = new AlertDialog.Builder(this);
alertConfirmTransfer.SetMessage("Confirm transfer");
alertConfirmTransfer.SetPositiveButton("Yes", delegate
{
    dialogConfirmTransfer.Cancel();
    //fire event call method MyMethod()
});


alertConfirmTransfer.SetNegativeButton("No", delegate
{
    dialogConfirmTransfer.Cancel();
});

dialogConfirmTransfer = alertConfirmTransfer.Create();
dialogConfirmTransfer.Show();

private void MyMethod()
{
    //the code I want to be executed after the event occurs
}

用户点击YES之后,我希望在对话框消失后触发一些事件,该事件调用一些位于OnCreate方法之外的MainActivity中的方法。互联网上有很多例子,但也许是因为我没有经常使用事件,我觉得很难将它应用到我的特定情况。你能给我提供我必须添加的代码,这样我就可以达到我的目的吗?

2 个答案:

答案 0 :(得分:0)

好吧,如果我没错,你想要做的就是在警告对话框上选择正面选择事件,我想这很容易,

您所要做的就是:

Dialog dialogConfirmTransfer = new Dialog(this);
AlertDialog.Builder alertConfirmTransfer = new AlertDialog.Builder(this);
alertConfirmTransfer.SetMessage("Confirm transfer");
alertConfirmTransfer.SetPositiveButton("Yes", delegate
{
 dialogConfirmTransfer.Cancel();
 myMethod();

});


alertConfirmTransfer.SetNegativeButton("No", delegate
{
  dialogConfirmTransfer.Cancel();
 });

dialogConfirmTransfer = alertConfirmTransfer.Create();
dialogConfirmTransfer.Show();

//call method

答案 1 :(得分:0)

我创建自定义EventHandler:

class FileTransferSuccessHandler
{
    public event EventHandler<EventArgs> OnFileTransferSuccess;
    public void FireEvent()
    {
        if (OnFileTransferSuccess != null)
        {
            OnFileTransferSuccess(this, new EventArgs());
        }
    }
}

我在代码中使用它来激活事件(调用方法)

FileTransferSuccessHandler fileTransferSuccessHandler = new FileTransferSuccessHandler();
fileTransferSuccessHandler.OnFileTransferSuccess += ImportDataIntoDatabase;
fileTransferSuccessHandler.FireEvent();

我写下要执行的代码:

private void ImportDataIntoDatabase(object sender, EventArgs e)
{
}