Android中使用lambda

参考网址:https://blog.csdn.net/u013197555/article/details/52775153

https://www.cnblogs.com/lizhilin2016/p/9237598.html

https://blog.csdn.net/u011781521/article/details/52702482

Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁。当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口

//没有使用Lambda
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.out.println("Actiondetected");
}
})
//使用Lambda:
button.addActionListener(()->{ 
System.out.println("Actiondetected");
});

使用步骤:

1.Android studio  File -> Project Structure -> Project > SDK Location:的JDK Location应该设置为JDK(1.8)的路径

2.根目录build.gradle中的buildscript节点下的dependencies下添加 'classpath 'me.tatarka:gradle-retrolambda:3.2.0'

3.打开app目录下的build.gradle 添加 apply plugin: 'me.tatarka.retrolambda'

4.打开app目录下的build.gradle 的android节点下添加  

 compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
  }

但是会报:Error:Jack is required to support java 8 language features. Either enable Jack或者遇到 Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompatibility JavaVersion.VERSION_1_8. 所以需要在build.gradle中添加以下

defaultConfig {
        jackOptions {
            enabled true
        }
}

说明:Android7.0(API24)在对JAVA8的支持上,需要使用新的编译器。


 

发布了19 篇原创文章 · 获赞 15 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/aidou1314/article/details/95036012
今日推荐