这是我的提醒:
new AlertDialog.Builder(Activity.this)
.setMessage("You have unsaved text. Are you sure you want to leave?")
.setCancelable(true)
.setNegativeButton("Leave", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
finish();
}
})
.setPositiveButton("Stay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
请注意我如何允许警报取消:.setCancelable(true)
如果用户按下后退按钮取消警报,我该如何运行一些代码?
答案 0 :(得分:2)
根据AlertDialog.Builder上的Android's website文档,您可以使用setOnCancelListener (DialogInterface.OnCancelListener onCancelListener)方法来处理取消对话框的时间。
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog)
{
// do what you need when the dialog is cancelled
}
})
因此,您的代码将更改为:
new AlertDialog.Builder(Activity.this)
.setMessage("You have unsaved text. Are you sure you want to leave?")
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog)
{
// do what you need when the dialog is cancelled
}
})
.setNegativeButton("Leave", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
finish();
}
})
.setPositiveButton("Stay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
}).show();