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的話,就會出現(xiàn)
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 central
repositories {
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
}
}