Android编译报错:androidx与com.android.support类重复问题求助
Hey there, let's work through this duplicate class issue you're facing—it's a super common hiccup when migrating to AndroidX after updating Android Studio/Gradle, so you're definitely not alone! The root problem here is that even though you've replaced your own com.android.support dependencies with AndroidX, some third-party libraries are still pulling in the old support libraries behind the scenes. Here's how to fix it step by step:
1. Identify Which Libraries Are Still Pulling In Support Dependencies
First, you need to pinpoint exactly which dependency is bringing in the old com.android.support:support-compat library. Run this command in your project's root directory:
- On macOS/Linux:
./gradlew app:dependencies - On Windows:
gradlew.bat app:dependencies
Scan the output for com.android.support:support-compat—you’ll see a dependency tree showing which parent library is including it (e.g., com.some.thirdparty:library:2.0.0).
2. Exclude Support Dependencies From Third-Party Libraries
Once you’ve found the culprit, add an exclusion rule to that dependency in your app-level build.gradle file. For example:
implementation('com.some.thirdparty:library:2.0.0') { // Exclude the specific conflicting module exclude group: 'com.android.support', module: 'support-compat' // Or exclude the entire support group if multiple modules cause issues // exclude group: 'com.android.support' }
3. Enable Jetifier in gradle.properties
Jetifier is a critical tool that automatically converts third-party libraries' support dependencies to AndroidX equivalents. Make sure these two lines are present and set to true in your project's gradle.properties file:
android.useAndroidX=true android.enableJetifier=true
This is often the missing piece—without Jetifier, excluded dependencies might sneak back in, or unupdated third-party libs won’t get converted to AndroidX.
4. Clean Up Caches and Rebuild
Old build caches can hold onto residual support library files, so let’s wipe them out completely:
- Run
./gradlew clean(orgradlew.bat cleanon Windows) from the command line. - Delete the
.gradlefolder in your project's root directory. - In Android Studio, go to File → Invalidate Caches... → Invalidate and Restart to clear IDE-level caches.
5. Verify Your Project's Configuration
Double-check your app-level build.gradle to ensure:
- Your
compileSdkVersionandtargetSdkVersionare set to 28 or higher (AndroidX fully replaced support libraries starting at API 28). - There are no remaining
com.android.supportdependencies—all should use AndroidX equivalents (e.g.,androidx.core:core-ktx:1.12.0instead ofcom.android.support:support-compat).
After following these steps, rebuild your project—the duplicate class errors should disappear!
内容的提问来源于stack exchange,提问作者TheKingElessar

