You might have made use of Toast to display messages that fades in stays for few seconds and fades away. If you want to display some message and let user select the response (Yes or No) then we can make use of Dialog called as AlertDialog.

AlertDialog is a subclass of Dialog from android.app package. You can create a dialog with one, two or even three buttons. It is also possible to display only text message using setMessage() method.
There are three functions for adding Buttons to Android Dialog,
setPositiveButton(int textId, DialogInterface.OnClickListener listener) :
This is Yes button, when clicked the code written in the OnClickListener onClick() method will be displayed.
setNegativeButton(int textId, DialogInterface.OnClickListener listener) :
This is just like the setPositiveButton method which acts a "NO" negative button, we will write the logic in OnClickListener anonymous class.
setNeutralButton(int textId, DialogInterface.OnClickListener listener) :
This is how we can set the 3rd button. It is a called the Neutral button.
Android AlertDialog SnippetAlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("AlertDialog Example");
builder.setMessage("This is an Example of Android AlertDialog with 3 Buttons!!");
//Button One : Yes
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Yes button Clicked!", Toast.LENGTH_LONG).show();
}
});
//Button Two : No
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "No button Clicked!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
//Button Three : Neutral
builder.setNeutralButton("Can't Say!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Neutral button Clicked!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
AlertDialog diag = builder.create();
diag.show();
This is not an AI-generated article but is demonstrated by a human on an M1 Mac running macOS Sonoma 14.0.
Please support independent contributors like Code2care by donating a coffee.
Buy me a coffee!

Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!