Kevin Chris Kevin Chris - 1 year ago 244
Android Question

Listener can be replaced with lambda

I have implemented an

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? Little help would be appreciated!


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Text", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

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

Answer Source

It means that you can shorten up your code:

example of onClickListener() without lambda :

mButton.setOnClickListener(new View.OnClickListener() {
    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 usefull when using alot of listeners or when writing code without an IDE. for more info check this

Hope this answeres your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download