可以用lambda代替侦听器是什么意思? [英] What does it mean that a Listener can be replaced with lambda?

查看:232
本文介绍了可以用lambda代替侦听器是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了AlertDialog,它具有正常的负和正按钮单击侦听器.

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

当我打电话给new DialogInterface.OnClickListener()时,它向我显示了一条建议:Anonymous new DialogInterface.OnClickListener() can be replaced with lambda.我知道这不是错误或重大错误,但这是什么建议,我该怎么办?

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 Studio V1.2.1.1 compileSdkVersion 22 buildToolsVersion "22.0.0" minSdkVersion 14 targetSdkVersion 22

推荐答案

这意味着您可以缩短代码.

It means that you can shorten up your code.

onClickListener() lambda的示例:

An example of onClickListener() without lambda:

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

可以用lambda 重写:

can be rewritten with lambda:

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

这是相同的代码.当使用大量侦听器或在没有IDE的情况下编写代码时,这很有用. 有关更多信息,请检查.

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.

这篇关于可以用lambda代替侦听器是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆