通话需要 api 等级 24 java.util.comparator

call requires api level 24 java.util.comparator

我在使用 Comparator 时遇到 api 级别的错误,但是当我添加 @RequiresApi(N) 注释时,错误就解决了。

问题是在添加@RequiresApi(N)注解后,这个应用程序不能运行在api level below 24,我在API 23 [=28]得到这个错误=]-

 Process: com.example.chatapp, PID: 13778
java.lang.NoClassDefFoundError: adapters.chatPageAdapter$$ExternalSyntheticLambda0
    at adapters.chatPageAdapter.onBindViewHolder(chatPageAdapter.java:59)
    at adapters.chatPageAdapter.onBindViewHolder(chatPageAdapter.java:25)
    at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
    at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
    at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)

那么,有什么方法可以让我在 23 岁以下的 api 上使用此方法甚至 运行 应用程序吗?

Build.Gradle -

android {
    compileSdk 30

buildFeatures {
    viewBinding true
}

defaultConfig {
    applicationId "com.example.chatapp"
    minSdk 23
    targetSdk 30
    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
}
}

您可以启用 desugarring - 它会启用较低的 api 版本以使用最新的 java8 功能。

在您的应用模块的 build.gradle 中,添加 coreLibraryDesugaringEnabled

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