why does the compiler show error for setPositiveButton and setNegativeButton in the code below. If I use setButton there is no error but that only allows me to show one button on the alert dialog. I want to have 2 buttons. According to many tutorials, a two button alert dialog must be set with setPositiveButton, and setNegativeButton. why are there compile erros for these?
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();
}
});
Your code is correct, only you need to change it little bit. Create AlertDialog using Builder class.