francozamp
francozamp

Reputation: 13

AlertDialog not showing at .show() - Xamarin Android

I have the following code:

private void CloseOrder(object sender, EventArgs e)
{
    Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(this);

    alert.SetTitle("Cerrar Pedido");
    alert.SetMessage("Are you sure?");
    alert.SetCancelable(true);
    alert.SetPositiveButton("Confirm", delegate { this.Rta = true; });
    alert.SetNegativeButton("Cancel", delegate { this.Rta = false; });
    Dialog dialog = alert.Create();
    dialog.Show();

    if (this.Rta)
    {
        //Some code here
    }

}

this.Rta is a property of my class.

The problem is that the alert doesn't show at dialog.show(), it shows once the method CloseOrder() ended, so this.Rta never gets the corresponding value assigned.

I've been searching a lot but I can't find a solution, if anyone can help me that'd be great!

Upvotes: 1

Views: 996

Answers (1)

Mike Ma
Mike Ma

Reputation: 2027

dialog.Show() is asynchronous method, that means CloseOrder(object sender, EventArgs e) and dialog.Show() end up at the same time.

You can not get the 'Rta' assigned value at the CloseOrder function.

You will get the value when you click the confirm or cancel button of the dialog.

I suggest you to use message sender in the delegate{this.Rta = true}

For example:

mHandler handler = new mHandler();
Message message = new Message();
message.What = 1;
alert.SetPositiveButton("Confirm", delegate { this.Rta = true; handler.SendMessage(message); });
alert.SetNegativeButton("Cancel", delegate { this.Rta = false; handler.SendMessage(message); });

//....

class mHandler : Handler{
        public override void HandleMessage(Message message) {
            switch (message.What) {
                case 1:
                     if (this.Rta)
                     {
                          //Some code here
                     }
                     break;
                }
            }
        }

Upvotes: 1

Related Questions