Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use lambda expression to create an AlertDialog

I have my Android studio set with these:

    classpath "me.tatarka:gradle-retrolambda:3.2.2"
    classpath 'me.tatarka.retrolambda.projectlombok:lombok.ast:0.2.3.a2'

And I am trying to use lambdas to know what I can do or not.

When I did the following code:

    alertDialogBuilder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

The IDE grayed out the new DialogInterface.OnClickListener() telling me it could be replaced with a lambda. Nothing more or less. After looking into several examples. I tried things like:

    alertDialogBuilder.setPositiveButton("Okay", (DialogInterface dialog) -> {
            dialog.cancel();
    });

Also these:

alertDialogBuilder.setNegativeButton((DialogInterface) d -> d.cancel());

Among the errors:

Error:(99, 64) error: incompatible types: DialogInterface is not a functional interface multiple non-overriding abstract methods found in interface DialogInterface

How should I use lambda in this case?

like image 795
DeMarco Avatar asked Jul 11 '26 21:07

DeMarco


1 Answers

onClick takes two parameters, and your example tries only show one. Be sure to include the which parameter in your lambda.

new AlertDialog.Builder(this).setPositiveButton("Okay", 
                                  (dialog, which) -> dialog.cancel());
like image 124
iagreen Avatar answered Jul 13 '26 12:07

iagreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!