Search code examples
javaandroid-studiolambda

How to replace anonymous OnClickListener with Lambda expression?


How an I replace this OnClickListener with a Lamda expression?

    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            User user=new User(etnewname.getText().toString(),
                    etnewtelp.getText().toString(),
                    etnewemail.getText().toString(),
                    etnewusername.getText().toString(),
                    etnewpassword.getText().toString());

See below for the Android Studio message, which I don't really understand.

enter image description here


Solution

  • Assuming you could outsource the creation of the User-Object into it's own method createAndStoreUser() and both parameters of the onClick(DialogInterface interface, int i)method will not be used, the annonymous class can be rewrittern as:

    alert.setPositiveButton("Yes", (di,i)-> createAndStoreUser());
    

    You could also define the concrete behvaiour directly within the lambda-expression. However this wouldn't bring many advantages:

    alert.setPositiveButton("Yes", (di,i)-> { User user = new User(...); ... });