在主Activity中加入以下代码:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { dialog(); return false; } return false; } protected void dialog() { AlertDialog.Builder builder = new AlertDialog.Builder(main.this); builder.setMessage("确定要退出吗?"); builder.setTitle("提示"); builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); main.this.finish(); } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); }
其实上面的代码只要是退出代码就行,我这里只是提供了一个方法,重点的在下面。
子activity中重载OnKeyDown函数,每个子activity中都要重载,代码如下:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { return false; }