Android 警报对话,如何让两个按钮都显示

Android 警报对话,如何让两个按钮都显示,android,dialog,android-alertdialog,Android,Dialog,Android Alertdialog,为什么编译器在下面的代码中显示setPositiveButton和setNegativeButton的错误。如果使用setButton,则不会出现错误,但这只允许我在警报对话框上显示一个按钮。我想要两个按钮。根据许多教程,必须使用setPositiveButton和setNegativeButton设置两个按钮的警报对话框。为什么会有编译错误 public void onClick(View v) { AlertDialog alert = new AlertDialo

为什么编译器在下面的代码中显示setPositiveButton和setNegativeButton的错误。如果使用setButton,则不会出现错误,但这只允许我在警报对话框上显示一个按钮。我想要两个按钮。根据许多教程,必须使用setPositiveButton和setNegativeButton设置两个按钮的警报对话框。为什么会有编译错误

    public void onClick(View v) {

        AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
        alert.setTitle("Confirm Edit");
        alert.setMessage("do you want to save edits?");

        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
            // launches other activity if the user presses the OK button
                Intent myIntent = new Intent(MainActivity.this, TestScreen.class);
             MainActivity.this.startActivity(myIntent);

           Toast.makeText(MainActivity.this, "Edits saved", Toast.LENGTH_SHORT).show();

            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Edits Canceled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        alert.show();


    }
});

您的代码是正确的,只需稍加修改即可。使用生成器类创建AlertDialog

Builder builder = new AlertDialog.Builder ( MainActivity.this ); 
builder.setTitle ( "Confirm Edit" ); 
builder.setMessage("do you want to save edits?");

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
            // launches other activity if the user presses the OK button
                Intent myIntent = new Intent(MainActivity.this, TestScreen.class);
             MainActivity.this.startActivity(myIntent);

           Toast.makeText(MainActivity.this, "Edits saved", Toast.LENGTH_SHORT).show();

            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Edits Canceled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });


// Now finally showing Alert Dialog.
AlertDialog alert = builder.create(); 
alert.show();