尝试显示对话框

时间:2014-09-26 14:29:53

标签: android

因此,当用户退出应用程序时,我正在尝试创建一个对话框,它会询问问题您确定要退出吗?应用程序退出但不显示对话框。

这是我的代码

public void exit(View view) {

        //  showDialog(ALERT_DIALOG1);
            final AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
            builder.setCancelable(false);
            builder.setMessage("Are you sure you want to quit");
            builder.setPositiveButton("Yes", null);   
    }             
            public void onClick(DialogInterface dialog, int id) {
                    Register.this.finish();
//                  builder.show();

 }
           };

2 个答案:

答案 0 :(得分:0)

将其放在退出功能上:

AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setCancelable(false);
builder.setMessage("Are you sure you want to quit");

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    // Setting positive button click action
    public void onClick(DialogInterface dialog, int id) {
         Register.this.finish(); 
    }
});

// Creating and then showing AlertDialog
AlertDialog alert = builder.create();
alert.show();

答案 1 :(得分:0)

此代码将在创建消息框之前检查后退按钮。

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Handle the back button
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            //Ask the user if they want to quit
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle(R.string.quit)
            .setMessage(R.string.really_quit)
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Stop the activity
                    YourClass.this.finish();    
                }

            })
            .setNegativeButton(R.string.no, null)
            .show();

            return true;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }

    }