繁体   English   中英

如何在android中使用lambda表达式

[英]How to use lambda expression in android

尝试使用 lambda 表达式时遇到此错误。

错误:

错误:(122, 42) 错误:-source 1.7 不支持 lambda 表达式(使用 -source 8 或更高版本启用 lambda 表达式)

我怎样才能解决它注意到我的 android studio 是 3.0

将以下代码添加到您的应用级别 gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

因为也许您正在使用 Java 7 而实际上, Retrolambda是一个我们可以与Java 8 lambda expressions一起使用的库。

那么如何设置:-

将以下内容添加到您project's main build.gradle

 classpath 'me.tatarka:gradle-retrolambda:3.2.3'

然后将此添加到your application module's build.gradle

apply plugin: 'me.tatarka.retrolambda'

然后我们需要将这些行添加到your application module's build.gradle

android {
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

完成后,您可以像下面一样使用它:-

例如。)单击带有 Retrolambda 的按钮。

  // RETROLAMBDA WAY
        clickMeBtn.setOnClickListener(view ->
                Toast.makeText(MainActivity.this,
             "This is the way to click a button to make a toast with RetroLambda !", Toast.LENGTH_LONG).show());

匿名类new View.OnClickListener()可以替换为lambda

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"

defaultConfig {
    applicationId "com.sanjay.sanjay"
    minSdkVersion 15
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

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

}

在你的app.gradle文件中添加这样的android studio

将以下块添加到您的应用程序级别 gradle 文件中

android {}属性

compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

喜欢

 android {
...
compileOptions {
            sourceCompatibility = '1.8'
            targetCompatibility = '1.8'
        }
}

使用以下代码并单击同步按钮,然后您的错误将被修复

 android { defaultConfig { // Required when setting minSdkVersion to 20 or lower multiDexEnabled true } compileOptions { // Flag to enable support for the new language APIs coreLibraryDesugaringEnabled true // Sets Java compatibility to Java 8 sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9' }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM