0

我在我的应用程序中实现了警报框。当在该状态下弹出警报框时, BACK按钮在应用程序中不起作用。请帮助我如何改写它。

代码::

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();
4

2 回答 2

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;
        }
    });
于 2013-07-02T04:47:06.133 回答
1

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

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();
于 2013-07-02T04:52:12.703 回答