显示AlertDialog时,后退按钮不起作用

时间:2018-04-03 07:31:42

标签: android alertdialog back-button

我想在按下后退按钮时销毁当前页面,但在显示AlertDialog时我的后退按钮不起作用。
我已经像下面一样实现了onBackPressed,但它仍然无法正常工作。

 private void showPopupSubscribe() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View dialogView = getLayoutInflater().inflate(R.layout.paket_subscribe, null);
    builder.setView(dialogView);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.logo_1);
    builder.setTitle(R.string.confirm);
    final RadioGroup radioGroup = dialogView.findViewById(R.id.rgSubscribe);

    builder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            pd.show();
            int selected = radioGroup.getCheckedRadioButtonId();
            if (selected == R.id.rbMonthly) {
                smsCode = "aa";
            } else if (selected == R.id.rbTwoWeeks) {
                smsCode = "bb";
            } else if (selected == R.id.rbWeekly) {
                smsCode = "cc";
            } else if (selected == R.id.rbTwoDays) {
                smsCode = "dd";
            }
            reqWebCharging(smsCode);
            dialog.dismiss();
        }
    });

    dialog = builder.create();
    dialog.show();
}

@Override
public void onBackPressed() {
    super.onBackPressed();

    if (dialog.isShowing()) {
        finish();
    }
}

2 个答案:

答案 0 :(得分:1)

当对话框显示时,您必须按下后退按钮

dialog.setOnKeyListener(new Dialog.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface arg0, int keyCode,
                    KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    dialog.dismiss();
                    finish();
                }
                return true;
            }
        });

同样 onBackPressed()应该是这样的

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

答案 1 :(得分:0)

这样做

@Override
public void onBackPressed() {

    if (dialog.isShowing()) {
        finish();
    else
        super.onBackPressed();

    }
}