[英]Xamarin: Close Alert Dialog when back button pressed
I'm new on Xamarin Android. 我是Xamarin Android的新手。 I have a Activity and when the textview is pressed an alert is showed. 我有一个活动,当按下textview时,显示警报。 The code of AlertDialog is: AlertDialog的代码是:
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. 我需要在按下“后退”按钮时,此事件关闭AlertDialog。 Thank You. 谢谢。
PD: I'm dev on Visual Studio 2012 + Plugin Xamarin PD:我是Visual Studio 2012 +插件Xamarin的开发人员
Editing (ρяσѕρєя K's Solution): 编辑(K的解决方案):
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. 这将继续显示警报,但是当按下“ back button
时,警报不会关闭。
I need when the Back Button be pressed, this event close the AlertDialog 我需要在按下“后退”按钮时,此事件关闭AlertDialog
To dismiss Dialog on back key press : 要关闭返回键上的对话框,请按:
1. Override OnBackPressed
. 1.覆盖OnBackPressed
。
2. Need to access alert
object in OnBackPressed
so declare alert
object before OnCreate
: 2.需要访问OnBackPressed
alert
对象,因此在OnCreate
之前声明alert
对象:
public override void OnBackPressed()
{
if (alert !=null){
if(alert.IsShowing){
alert.Dismiss ();
}else{
base.OnBackPressed();
}
}else{
base.OnBackPressed();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.