我尝试覆盖 onkeydown()方法以及 onBackPressed()方法但是警告对话框不会显示而是只返回到以前的意图。我尝试了几个例子,但没有一个有效。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
Log.d("confirm save method","");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("");
builder.setMessage("Do you want to Save the Game ?");
builder.setCancelable(false);
builder.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
builder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
Log.d("confirm save method","");
}
答案 0 :(得分:1)
onBackPressed
,则不必覆盖onKeyDown(int keyCode, KeyEvent event)
。这很复杂。删除此方法(onKeyDown
)可以解决此问题。提示2:return true
来中断此关键事件。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
alertAialog();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void alertDialog(){
...
}
答案 1 :(得分:0)
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setTitle("Exit Alert")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//finishAffinity();
finish(); //or do anything
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
尝试此代码,并删除onKeyDown();