@Override
/**
* 监听返回键 重写退出弹框
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK) {
//创建退出对话框
AlertDialog isExit = new AlertDialog.Builder(this).create();
//设置对话框标题
isExit.setTitle("系统提示");
//设置对话框消息
isExit.setMessage("确定要退出吗?");
//添加选择按钮添加监听事件
isExit.setButton("确定", listener);
isExit.setButton2("取消", listener);
//显示对话框
isExit.show();
}
return false;
}
//监听对话弹框的按钮事件
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
//选择了确定按钮
case AlertDialog.BUTTON_POSITIVE:
finish();
break;
//选择了取消按钮
case AlertDialog.BUTTON_NEGATIVE:
break;
default:
break;
}
}
};ANDROID 监听返回键,重写事件
最新推荐文章于 2025-08-31 16:02:59 发布
本文介绍了一种在Android应用中通过监听返回键并显示退出确认对话框的方法。该方法利用了AlertDialog.Builder来创建对话框,并设置了两个按钮:确定和取消,分别对应退出应用和取消操作。
1013

被折叠的 条评论
为什么被折叠?



