Android Studio报错"Lambda表达式不支持语言级别7"的解决方法咨询
Hey there, let's get that Lambda expression error sorted out for you! The root cause here is that your Android project is configured to use Java 7, which doesn't support Lambda syntax—those are a Java 8 feature. Here's how to update your project settings to fix this:
Step 1: Update your module-level build.gradle file
Navigate to your app module's build.gradle file (not the root project's build.gradle) and add the compileOptions block inside the android section. If you're using Kotlin in your project, add the kotlinOptions block too to keep everything aligned:
android { // Your existing configuration (like compileSdk, defaultConfig, etc.) goes here compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } // Only add this if you're using Kotlin kotlinOptions { jvmTarget = "1.8" } }
Step 2: Sync your Gradle project
After making the changes, click the "Sync Now" button that pops up in the top-right corner of Android Studio. Wait for the sync to complete—this applies the new Java version settings to your project.
Step 3: Verify Project Structure (optional)
To double-check everything is set correctly:
- Go to
File > Project Structure(or use the shortcutCtrl+Alt+Shift+Son Windows/Linux,Cmd+;on Mac) - Select your app module under "Modules" on the left
- Switch to the "Properties" tab
- Set both Source Compatibility and Target Compatibility to
1.8
Once these steps are done, your Lambda expression (like the one in your code):
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener((view) -> { showDialog(); //Intent cartIntent = new Intent(Home.this, Cart.class); //startActivity(cartIntent); });
will be recognized without errors, since Java 8 fully supports Lambda syntax.
内容的提问来源于stack exchange,提问作者KDD

