根据产品设计的需求,有时需要在程序主界面按手机的返回实体键时,出现一个确认退出的对话框。
以下代码实现该功能,且可以放在任何一个Activity中使用。
@Override
publicboolean onKeyDown(int keyCode, KeyEvent event) {
// 按下键盘上返回按钮
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setTitle("Message Box")
.setMessage("Sure to exit?")
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
returntrue;
} else {
returnsuper.onKeyDown(keyCode, event);
}
}
publicboolean onKeyDown(int keyCode, KeyEvent event) {
// 按下键盘上返回按钮
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setTitle("Message Box")
.setMessage("Sure to exit?")
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
returntrue;
} else {
returnsuper.onKeyDown(keyCode, event);
}
}