添加资源后构建失败,Android Studio中如何正确放置res目录资源?
Hey there! I totally get the frustration when older book instructions don't line up with the latest Android Studio changes—this is super common as Google updates the IDE and project structure regularly. Let me break down how to fix this and get your image resources set up correctly with the current setup:
Why You're Seeing the Gradle Error
Back when John Horton's book was published, Android Studio's default project structure was a bit different. Today, projects use a module-based structure where all your app's resources (like images) belong in the app/src/main/res directory, not a top-level res folder. Worse, just dropping images directly into the res root won't work—Gradle expects resources to be organized into subdirectories based on their type (e.g., drawable for images, layout for UI files).
Step-by-Step to Correctly Add Your Images
Follow these steps to get your resources in the right place:
- First, switch to the Android view in Android Studio (use the dropdown menu in the top-left corner of the Project pane—this is the most intuitive view for modern projects).
- Navigate to
app > res, right-click theresfolder, then select New > Android Resource Directory. - In the popup window:
- Set Resource type to
drawable(this is the standard folder for general images; if you need density-specific versions, pick the appropriate option likedrawable-hdpi). - Leave the other settings as default, then click OK.
- Set Resource type to
- Copy your downloaded images into this new
drawable(or density-specific) folder. Make sure your filenames follow Android's rules: only lowercase letters, numbers, underscores, and hyphens—no spaces or uppercase characters! - Finally, sync your project with Gradle: click the elephant icon (
Sync Project with Gradle Files) in the top toolbar.
Quick Troubleshooting Checks
If you still run into errors after following the steps above:
- Double-check your
build.gradle (Module: app)file to ensure it's pointing to the correct resource directory. The default setup should look like this:android { // ... other configs sourceSets { main { res.srcDirs = ['src/main/res'] } } } - If you were using the Project view instead of Android view, confirm your images are in
app/src/main/res/drawable(not aresfolder at the project root). - Clean and rebuild your project: go to Build > Clean Project, then Build > Rebuild Project—this fixes cached Gradle issues sometimes.
Bonus: Use Android Studio's Built-in Tools
Instead of manually copying files, let Android Studio handle the resource setup for you:
- Right-click the
resfolder and select New > Image Asset (for app icons or adaptive icons) or New > Vector Asset (for scalable vector graphics). - These tools will automatically place your resources in the correct directories and even generate density-specific versions if needed, which saves you from manual errors.
内容的提问来源于stack exchange,提问作者siddhesh

