@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 按下的如果是BACK,同时没有重复
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
AlertDialog.Builder builder = new Builder(this);
builder.setMessage("您确定要退出?");
builder.setTitle("提示");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
Activity01.this.finish();
}
});
builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
dialog.dismiss(); //取消对话框
}
});
AlertDialog alertDialog = builder.create();
//设置这个对话框不能被用户按[返回键]而取消掉,但测试发现如果用户按了KeyEvent.KEYCODE_SEARCH,对话框还是会Dismiss掉
alertDialog.setCancelable(false);
//由于设置alertDialog.setCancelable(false); 发现如果用户按了KeyEvent.KEYCODE_SEARCH,对话框还是会Dismiss掉,这里的setOnKeyListener作用就是屏蔽用户按下KeyEvent.KEYCODE_SEARCH
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
} else {
return false; // 默认返回 false
}
}
});
alertDialog.show();
}
return super.onKeyDown(keyCode, event);
}
android捕获back返回键
最新推荐文章于 2024-08-20 23:20:42 发布