Kevin F
Kevin F

Reputation: 169

Xamarin: Close Alert Dialog when back button pressed

I'm new on Xamarin Android. I have a Activity and when the textview is pressed an alert is showed. The code of AlertDialog is:

textView1.Click += (sender, e) =>
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("title");
                alert.SetMessage("Message");
                alert.SetCancelable(false);
                alert.SetPositiveButton("Cerrar Sesión", delegate { funcCerrarSesion(); });
                alert.SetNegativeButton("Salir", delegate { Finish(); });
                alert.SetNeutralButton("Volver", delegate {  });

                RunOnUiThread(() =>
                {
                    alert.Show();
                });
            };

I need when the Back Button be pressed, this event close the AlertDialog. Thank You.

PD: I'm dev on Visual Studio 2012 + Plugin Xamarin

Editing (ρяσѕρєя K's Solution):

    Dialog dialog;
            protected override void OnCreate(Bundle bundle)
            {
..
textView1.Click += (sender, e) =>
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Advertencia");
                alert.SetMessage("Está seguro?");
                alert.SetCancelable(false);
                alert.SetPositiveButton("Cerrar Sesión", delegate { funcCerrarSesion(); });
                alert.SetNegativeButton("Salir", delegate { Finish(); });
                alert.SetNeutralButton("Volver", delegate {  });

                RunOnUiThread(() =>
                {
                    dialog = alert.Create();
                    dialog.Show();
                });
            };
...
}

public override void OnBackPressed()
        {
            if (dialog != null)
            {
                if (dialog.IsShowing)
                {
                    dialog.Dismiss();
                }
                else
                {
                    base.OnBackPressed();
                }
            }
            else
            {
                base.OnBackPressed();
            }
        }

This continue showing the alert but when back button is pressed, the alert not close.

Upvotes: 2

Views: 9176

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

I need when the Back Button be pressed, this event close the AlertDialog

To dismiss Dialog on back key press :

1. Override OnBackPressed.

2. Need to access alert object in OnBackPressed so declare alert object before OnCreate :

public override void OnBackPressed()
{
    if (alert !=null){
       if(alert.IsShowing){
          alert.Dismiss ();
        }else{
          base.OnBackPressed();
        }
     }else{
        base.OnBackPressed();
     }
}

Upvotes: 2

Related Questions