Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlertDialog with OK/Cancel buttons

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.

like image 284
smartmouse Avatar asked Aug 26 '14 11:08

smartmouse


2 Answers

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();
like image 170
Blackbelt Avatar answered Sep 23 '22 21:09

Blackbelt


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

like image 30
Asif Mujteba Avatar answered Sep 24 '22 21:09

Asif Mujteba