警报框存在时,后退按钮不起作用

时间:2013-07-02 04:44:21

标签: android alertdialog android-alertdialog

我在我的应用程序中实现了警报框。当警报框弹出时, BACK 按钮在应用程序中无法正常工作。请帮我解决这个问题。

CODE ::

AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(this);
    alertDialogBuilder2.setTitle("EXIT");

    alertDialogBuilder2.setMessage("ARE YOU SURE?").setCancelable(false)

    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            finish();
            Toast.makeText(getApplicationContext(), "TAKE CARE and BYE",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
      })
    .setNegativeButton("No",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            dialog.cancel();
        }
    });


    AlertDialog alertDialog2 = alertDialogBuilder2.create();
    alertDialog2.show();

2 个答案:

答案 0 :(得分:1)

尝试设置

alertDialogBuilder2.setCancelable(true);

另一种解决方案:

  alertDialogBuilder2.setOnKeyListener(new OnKeyListener() {

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

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

答案 1 :(得分:1)

您应该将方法dialog.cancel()更改为dialog.dismiss()

AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(this);
     alertDialogBuilder2.setTitle("EXIT");

     alertDialogBuilder2.setMessage("ARE YOU SURE?").setCancelable(false)

    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            finish();
            Toast.makeText(getApplicationContext(), "TAKE CARE and BYE",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |     Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
      })
    .setNegativeButton("No",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            dialog.dismiss();
        }
    });


    AlertDialog alertDialog2 = alertDialogBuilder2.create();
    alertDialog2.show();