Android Studio 3.1.4:不支持 java.time.LocalDate"

Android Studio 3.1.4: java.time.LocalDate" is not supported

Android Studio 3.1.4,Java 8,Gradle 4.4.

在我的 build.gradle:

        compileSdkVersion 26
        minSdkVersion 18
        targetSdkVersion 26

      compileOptions {
            targetCompatibility JavaVersion.VERSION_1_8
            sourceCompatibility JavaVersion.VERSION_1_8
        }

        implementation 'com.android.support:appcompat-v7:26.1.0'

在我的 POJO 中

import java.time.LocalDate;
import java.util.Date;
public class Product {
    private Date redeemed_date;
    private LocalDate myLocalDate;
}

我必须使用 minSdkVersion 18 因为这是客户要求。

但是构建时出现错误:

error: Field "myLocalDate" of type "java.time.LocalDate" is not supported.

The JavaDocs for LocalDate 显示它是在 API 级别 26 中添加的。您的 minSdkVersion 低于该级别,因此 LocalDate 将不会在所有设备上受支持你想 运行 on.

您的选择是:

  1. 将您的 minSdkVersion 提高到 26,或者

  2. 用别的东西,比如ThreeTenABP, that

自 2020 年 4 月起,使用 Android Gradle 插件 4.0.0,您可以启用对 Java 8 种语言的支持API(查看所有支持的 API:https://developer.android.com/studio/write/java8-support-table

To enable support for these language APIs on any version of the Android platform, update the Android plugin to 4.0.0 (or higher) and include the following in your module’s build.gradle file:

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'
}

来源:https://developer.android.com/studio/write/java8-support