Android 使用 lambda 表达式
16lz
2021-01-23
Android Studio 3.0 开始可以支持java8了,不需要添加jack或者使用retrolambda了
jdk 1.8 新增了 lambda 表达式的特性,想要在android中使用lambda,需要以下几步。
- 安装jdk1.8
- 在build.gradle中添加以下代码
android { compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 }}
或者你可以按快捷键Ctrl+Shift+Alt+S进入 Project Structure
在你的 Modul e的 Source Compatibility 和 Target Compatibility 栏中填写 1.8。
apply 之后项目会自动同步,并在 build.gradle 中生成上面的代码。
- 但是报错了:
Error:Jack is required to support java 8 language features
需要在build.gradle中添加以下代码
defaultConfig { ... jackOptions { enabled true } }
这样就能通过了
- 但如果你使用了dataBinding的话,就会出现
Error:Data Binding does not support Jack builds yet
所以如果你使用了dataBinding的话以上方法就不适合你了。请使用 retrolambda。这里我贴上 retrolambda 的官方说明。
- Download jdk8.
- Add the following to your build.gradle
buildscript { repositories { mavenCentral() }dependencies { classpath 'me.tatarka:gradle-retrolambda:3.5.0' }}// Required because retrolambda is on maven centralrepositories { mavenCentral()}apply plugin: 'com.android.application' //or apply plugin: 'java'apply plugin: 'me.tatarka.retrolambda'
alternatively, you can use the new plugin syntax for gradle 2.1+
plugins { id "me.tatarka.retrolambda" version "3.5.0"}
The plugin will compile the source code with java8 and then replace the class files with the output of retrolambda.
- Add these lines to your build.gradle to inform the IDE of the language level.
android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }}
更多相关文章
- Mac下的android studio快捷键
- Android开发人员不得不收集的代码(blankj:utilcode)
- Android第五十二期 - 云之讯的代码混淆
- Android 使用自定义注解代替重复写findViewById代码
- Android代码风格指导
- android基础-界面代码
- 【Android】Lambda表达式
- 整理出15个Android很有用的代码片段