@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //back key Constant Value: 4 (0x00000004) //创建退出对话框 AlertDialog.Builder isExit = new AlertDialog.Builder(this); //设置对话框标题 isExit.setTitle("消息提醒"); //设置对话框消息 isExit.setMessage("确定要退出吗"); // 添加选择按钮并注册监听 isExit.setPositiveButton("确定", diaListener); isExit.setNegativeButton("取消", diaListener); //对话框显示 isExit.show(); } return false;
DialogInterface.OnClickListener diaListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int buttonId) { // TODO "确认和退出事件" switch (buttonId) { case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序 finish(); break; case AlertDialog.BUTTON_NEGATIVE:// "退出"按钮什么也不做 break; default: break; } } };