Search code examples
androidandroid-dialog

Android: Passing parameters to Alert Dialog


I am showing a simple Alert Dialog with OK/Cancel buttons. When user clicks OK, some code runs - that needs a parameter.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        MainActivity.this);
        alertDialogBuilder
        .setTitle("Are you sure?")
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //TODO: Do something with parameter.
            }
        })
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();

                    }
                });

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();

How do i pass the parameter to AlertDialog?


Solution

  • If you declare the variable as final then you can set it in your code before calling AlertDialog.Builder() and then access it in the onClick(), like this:

        final int someParameter = someValue;
    
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this);
                alertDialogBuilder
                .setTitle("Are you sure?")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Do something with parameter.
                        doSomeStuff(someParameter);
                    }
                })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
    
                            }
                        });
    
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
    
        // show it
        alertDialog.show();
    

    This way, someParameter is implicitly passed to onClick() via a function closure, so there is no need to subclass AlertDialog or add extra member variables to your Activity.