I have migrated my project to androidX, and I want to implement an alert dialog with positive and negative feedback from the user.
I am using this code:
AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("MSG", "onClick: YES");
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Log.d("MSG", "onClick: No");
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
But I get this error when running the app:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
You can use the MaterialAlertDialogBuilder
provided by the Material Components library.
Just use:
new MaterialAlertDialogBuilder(context)
.setTitle("Dialog")
.setMessage("Write your message here. ....")
.setPositiveButton("Ok", /* listener = */ null)
.setNegativeButton("Cancel", /* listener = */ null)
.show();
The MaterialAlertDialogBuilder
requires a Material theme and will result in an androidx.appcompat.app.AlertDialog
.