Android多Gradle模块下代码无法跨模块获取资源问题咨询
Hey there, let's work through this R reference issue you're hitting in your feature module. I've dealt with similar multi-module Android project quirks before, so here's what's probably going on and how to fix it:
1. Double-Check Your Dependency Structure
First, let's confirm your module dependencies are set up correctly. You mentioned the chain is app ← coremodule ← featuremodule — but if your feature module needs to access resources from coremodule, featuremodule should depend on coremodule, not the other way around.
If coremodule is currently depending on featuremodule, that's backwards. To fix this:
- Open your featuremodule's
build.gradle(orbuild.gradle.kts) file - Add a dependency on coremodule:
dependencies { implementation project(":coremodule") } - Remove the coremodule's dependency on featuremodule if it exists
This way, featuremodule has proper access to coremodule's resources, and the generated R class in featuremodule will include references to coremodule's resources.
2. Ensure Core Module is Configured as a Library
Coremodule needs to be an Android Library module (not an Application module) to share resources with other modules. Check its build.gradle file:
- Make sure the plugin is
com.android.library(notcom.android.application):plugins { id 'com.android.library' // ... other plugins like kotlin-android }
If it was set as an application module, switching it to a library will let other modules properly consume its resources.
3. Verify R Class Import in Feature Module Code
Sometimes the issue is just an incorrect import for the R class. In your feature module's Activity:
- Make sure you're importing the feature module's own R class, not the coremodule's or app's:
import com.yourpackage.featuremodule.R // Correct // import com.yourpackage.coremodule.R // Wrong, don't do this
When featuremodule depends on coremodule, its generated R class will include all resources from coremodule, so you can reference them directly like R.string.res_from_core_module.
4. Clean and Rebuild the Project
Android Studio's Gradle cache or generated R classes can sometimes get out of sync. Try these steps:
- Go to
Build > Clean Project - Then
Build > Rebuild Project - You can also invalidate caches with
File > Invalidate Caches... > Invalidate and Restart
This often fixes weird R reference issues caused by stale generated files.
5. Check for Resource Naming Conflicts
If you have resources with the same name in featuremodule and coremodule, that can cause R class generation issues. For example, if both modules have a string named app_name, the featuremodule's R class might prioritize its own, or cause confusion.
Double-check that your coremodule's resource names are unique, or use prefixes (like core_) to avoid conflicts.
内容的提问来源于stack exchange,提问作者Mikhail Sidorov

