转载自: http://blog.csdn.net/xue_wei_love/article/details/6881978
现有一个activity,并且有dialog弹出(如图)。
当在dialog存在的时候,点击手机back键,先退出的是此dialog,当再次点击手机返回键的时候,才能退出此activity。
那么如何写代码实现只点击一次手机back键时,退出当前activity?
实现:
private AlertDialog mDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_alert_text);
builder.setMessage(R.string.net_alert_text);
builder.setPositiveButton(R.string.setting,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setNegativeButton(R.string.cancanl,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Loading.this.finish();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Loading.this.finish();
}
});
mDialog = builder.create();
mDialog.show();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
mDialog.dismiss();
Loading.this.finish();
}
return super.onKeyDown(keyCode, event);