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

前端 未结 3 1802
一个人的身影
一个人的身影 2020-12-25 09:11

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

When I called new DialogInterface.OnClickListener()

相关标签:
3条回答
  • 2020-12-25 10:03

    Its as simple as this:

    button.setOnClickListener(view -> username = textView.getText());
    
    0 讨论(0)
  • 2020-12-25 10:06

    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.

    0 讨论(0)
  • 2020-12-25 10:11

    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.

    0 讨论(0)
提交回复
热议问题