What does it mean that a Listener can be replaced with lambda?

AndroidLambdaAndroid Alertdialog

Android Problem Overview


I have implemented an AlertDialog with normal negative and positive button click listeners.

When I called new DialogInterface.OnClickListener() it was showing me a suggestion saying: Anonymous new DialogInterface.OnClickListener() can be replaced with lambda. I know it's not an error or something big but what exactly is this suggestion and what can I do about it?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Text", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // do something here
    }
});

Android Studio V1.2.1.1 compileSdkVersion 22 buildToolsVersion "22.0.0" minSdkVersion 14 targetSdkVersion 22

Android Solutions


Solution 1 - Android

It means that you can shorten up your code.

An example of onClickListener() without lambda:

mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // do something here
    }
});

can be rewritten with lambda:

mButton.setOnClickListener((View v) -> {
    // do something here
});

It's the same code. This is useful when using a lot of listeners or when writing code without an IDE. For more info, check this.

Hope this answers your question.

Solution 2 - Android

Its as simple as this:

button.setOnClickListener(view -> username = textView.getText());

Solution 3 - Android

To replace the classic new DialogInterface.OnClickListener() implementation with lambda expression is enough with the following

 builder.setPositiveButton("resourceId", ((DialogInterface dialog, int which) -> {
      // do something here
 }));
    

It´s just taking the onClick event parameters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKavin PrabhuView Question on Stackoverflow
Solution 1 - AndroidStriderView Answer on Stackoverflow
Solution 2 - AndroidLEMUEL ADANEView Answer on Stackoverflow
Solution 3 - AndroidGabriel PerezView Answer on Stackoverflow