在Java8中新增加了对lambda的支持。但是AndroidStudio默认是不支持的。需要借助第三方实现对lambda的支持。
1、在项目的 build.gradle 中添加 classpath 'me.tatarka:gradle-retrolambda:3.2.0' 。加入编译的依赖。
添加后:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'me.tatarka:gradle-retrolambda:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
2、在app的 build.gradle 中加入plugin声明。 apply plugin: 'me.tatarka.retrolambda' 。
3、 在app的 build.gradle 中加入compileOptions,这会让IDE使用用JAVA8语法解析。
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
4、指定将源码编译的级别,将代码兼容1.7
retrolambda {
javaVersion JavaVersion.VERSION_1_7
}
最终版:
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
retrolambda {
javaVersion JavaVersion.VERSION_1_7
}
allprojects {
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
}