I create this AlertDialog:
String msg = "Connessione lenta o non funzionante";
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(HomePage.this).create();
alertDialog.setTitle("Timeout connessione");
alertDialog.setMessage(msg);
alertDialog.show();
I want to add OK and Cancel buttons. I searched here on StackOverflow but setButton method seems to be deprecated. I also found setPositiveButton and setNegativeButton for AlertDialog.Builder but even them seem to be deprecated.
You can use AlertDialog.Builder.setPositiveButton
and AlertDialog.Builder.setNegativeButton
, both are not deprecated (see the documentation):
new AlertDialog.Builder(HomePage.this)
.setTitle("Timeout connessione")
.setMessage("Connessione lenta o non funzionante")
.setNegativeButton(android.R.string.cancel, null) // dismisses by default
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
// do the acknowledged action, beware, this is run on UI thread
}
})
.create()
.show();
Use alertDialog.setPositiveButton
and alertDialog.setNegativeButton
, Here is a Utility Method you can use:
public static void ask(final Activity activity, String title, String msg,
DialogInterface.OnClickListener okListener,
DialogInterface.OnClickListener cancelListener) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
alertDialog.setTitle(title);
alertDialog.setMessage(msg);
alertDialog.setPositiveButton(R.string.ok, okListener);
alertDialog.setNegativeButton(R.string.cancel, cancelListener);
alertDialog.show();
}
You can call it like this:
ask(mInstance, getString(R.string.app_name),
getString(R.string.confirm_text_here),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { // OK
// do Something
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { // Cancel
// do Something
}
});
For more details refer Android Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With