Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 364
Kavin Prabhu Avatar asked Jun 10 '15 09:06

Kavin Prabhu


People also ask

Can be replaced with lambda in Android Studio?

If you want to replace all the lambda expression from the project you can try Ctrl + Shift+ Alt + I on inspection search tab, search anonymous type can be replaced with lambda. It will replace all the anonymous type to lambda. With Studio 3.5.

Can be replaced with lambda Java?

Since the most common use of Anonymous class is to provide a throwaway, stateless implementation of abstract class and interface with a single function, those can be replaced by lambda expressions, but when you have a state field or implementing more than one interface, you cannot use lambdas to replace the anonymous ...


3 Answers

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.

like image 104
Strider Avatar answered Oct 06 '22 17:10

Strider


Its as simple as this:

button.setOnClickListener(view -> username = textView.getText());
like image 24
LEMUEL ADANE Avatar answered Oct 06 '22 18:10

LEMUEL ADANE


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.

like image 5
Gabriel Perez Avatar answered Oct 06 '22 16:10

Gabriel Perez