运行Android应用出现Attr/colorPrimary重复定义错误求助
Hey there, let's tackle this frustrating duplicate attribute error you're facing. This issue almost always boils down to either a duplicate declaration in your own code, a dependency conflict, or a corrupted Gradle cache. Here's how to fix it step by step:
1. Check Your Local Resource Files for Duplicate Declarations
First, head to your project's res/values folder and look for files like attrs.xml or values.xml. Search for <attr name="colorPrimary" ...> — if you see this line more than once, delete the duplicate entry.
Remember: colorPrimary is already defined by the AppCompat-v7 library, so you don't need to declare it yourself in attrs.xml. You only need to set its value in your theme (like in styles.xml).
2. Resolve Dependency Conflicts
Sometimes a third-party library you're using might also include a version of AppCompat or define the same colorPrimary attribute, causing a conflict. To diagnose this:
- Open Android Studio's Terminal and run the dependency tree command:
# Windows gradlew.bat app:dependencies # macOS/Linux ./gradlew app:dependencies - Look for duplicate entries of
com.android.support:appcompat-v7(orandroidx.appcompat:appcompatif you're using AndroidX). If you find one, exclude the duplicate from the problematic library in yourbuild.gradle (Module level):implementation('com.example.thirdparty:library:1.0.0') { exclude group: 'com.android.support', module: 'appcompat-v7' }
3. Clean Gradle Cache and Rebuild the Project
Corrupted Gradle cache files often cause weird resource duplication errors. Try these steps:
- Delete the cache folder mentioned in your error:
C:\Users\jonat\.gradle\caches\transforms-1 - In Android Studio, go to
File > Invalidate Caches...and select Invalidate and Restart - After the IDE restarts, run
Build > Clean Projectfollowed byBuild > Rebuild Project
4. Verify Your Theme Setup
Double-check your app's theme in styles.xml to make sure you're not accidentally redefining the attribute:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Correct: Set the value of the existing colorPrimary attribute --> <item name="colorPrimary">@color/your_custom_primary_color</item> <!-- Wrong: Don't declare the attribute here or in attrs.xml --> <!-- <attr name="colorPrimary" format="color" /> --> </style>
If you follow these steps, the duplicate colorPrimary error should disappear. Let me know if you hit any snags!
内容的提问来源于stack exchange,提问作者Jonathan Souza

