AlertDialog setButton was deprecated
Java
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(Dialog.BUTTON_POSITIVE,"OK",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
Kotlin
var alert: AlertDialog = AlertDialog.Builder(this).create()
alert.setTitle("Error")
alert.setMessage("Sorry, your device doesn't support flash light!")
alert.setButton(Dialog.BUTTON_POSITIVE, "OK", DialogInterface.OnClickListener {
//do your own idea.
dialog, which -> finish() })
alert.show()
You can use this but better use a AlertDialog.Builder next time.
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog=new AlertDialog.Builder(getApplicationContext()).create();
alertDialog.setTitle("Hello");
alertDialog.setMessage("Hai");
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "hai", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Thanks", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
To make sure your dialogs match the design guidelines, the API now has 3 types of buttons for an AlertDialog: BUTTON_POSITIVE, BUTTON_NEUTRAL and BUTTON_NEGATIVE. This also provides correct positions for right to left support.
I would advice to create your AlertDialog
with the builder pattern
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);//Context parameter
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do stuff
}
});
builder.setMessage("some message");
AlertDialog alertDialog = builder.create();
More information on the AlertDialog.Builder
can be found in the API reference