onBackPressed不能与AlertDialog一起使用

时间:2017-03-04 18:02:28

标签: android android-alertdialog

我的代码显示一个AlertDialog,按下肯定按钮退出活动。我希望它能够退出后退按钮。但是当我.setCancelable(false)时,我的onBackPressed不起作用。如何在不将其更改为.setCancelable(true)

的情况下解决此问题
// show in dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("BROADCAST")
            .setMessage(text)
            .setCancelable(false)
            .setPositiveButton("Dismiss",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

@Override
public void onBackPressed() {
    finish();
}

2 个答案:

答案 0 :(得分:3)

容易撒尿..

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BROADCAST")
        .setMessage(text)
        .setCancelable(true)
        .setPositiveButton("Dismiss",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                })
        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    finish();
                                }
                            });
AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false);
alert.show();

答案 1 :(得分:2)

你可以设置一个关键监听器

builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                    if(keyCode == KeyEvent.KEYCODE_BACK){
                        dialog.dismiss(); // dismiss the dialog
                       YourActivity.this.finish(); // exits the activity

                    }

                    return true;
                }
            })