Android Studio 使用Lambda表达式

Java7是默认不能使用Lambda,但是可以通过插件让Android使用Lambda。

第一步,安装Java8,并指定项目使用Java8,只能使用Java8 的 Lambda特性。

Android Studio 使用Lambda表达式_第1张图片

第二步,打开模块build.gradle:

在根上添加

apply plugin: 'me.tatarka.retrolambda'

打开项目build.gradle

buildscript {
    repositories {
//        mavenCentral()
        maven {
            url "http://maven.oschina.net/content/groups/public"
        }
    }

    dependencies {
        classpath 'me.tatarka:gradle-retrolambda:2.5.0'
    }
}


打开模块build.gradle

在android区域添加

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

试试效果怎么样

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
    fab.setOnClickListener(view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show());
}

这样就清爽多啦。。。


你可能感兴趣的:(Java,Android)