最近一直想要按返回键,弹出对话框然后选择退出,或者是继续留在当前Activity
查了之后发现要重载onKeyDown()函数,下面写代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("确定退出");
builder.setMessage("测试用例");
//设置确定按钮
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//设置取消按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//do nothing
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
//下面代码是Eclipse自动添加的,返回的是执行Activity的onKeyDown()返回的值
// return super.onKeyDown(keyCode, event);
}
2.下面是onKeyDown(keyCode, event)
函数中第一部分代码
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (getApplicationInfo().targetSdkVersion
>= Build.VERSION_CODES.ECLAIR) {
event.startTracking();
} else {
onBackPressed();
}
return true;
}
从此函数中我们可以看出,如果不重载的话,代码将会执行返回,直到退出Activity栈。因此要把return的返回值自己重写