Android开发:LinearLayout与CollapsingToolbarLayout背景图报错求助
Hey there! Let’s fix that @drawable/img background error you’re hitting as an Android beginner. This issue almost always boils down to a few common missteps—let’s walk through each one to get your images showing up correctly.
Common Causes & Fixes
1. Double-check your image resource exists
- Make sure you actually have an image named
img(exact spelling, case-sensitive!) in yourres/drawablefolder. Android treatsImg.pngandimg.pngas totally different files, so watch those capital letters. - Stick to supported formats: PNG, JPG, or WebP work best. If you’re using an SVG, you’ll need to place it in
drawable-v24or useVectorDrawableCompatfor backward compatibility.
2. Verify your XML reference is correct
- For
LinearLayout, the background should be set like this (no typos!):android:background="@drawable/img" - For
CollapsingToolbarLayout, you might be usingapp:contentScrimor anImageViewas the parallax background. Don’t forget to declare theappnamespace at the top of your layout file:
Here’s a valid CollapsingToolbarLayout setup with an image:xmlns:app="http://schemas.android.com/apk/res-auto"<com.google.android.material.appbar.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="280dp" app:contentScrim="@drawable/img" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <!-- Parallax background image --> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/img" app:layout_collapseMode="parallax"/> <androidx.appcompat.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin"/> </com.google.android.material.appbar.CollapsingToolbarLayout>
3. Clean & rebuild your project
Android Studio’s resource cache can sometimes glitch out. Head to the top menu:
- Click
Build > Clean Project - Then
Build > Rebuild Project
This forces Studio to reprocess all your resources, which often fixes "missing" resource errors.
4. Ensure your filename follows Android rules
Resource filenames can only use lowercase letters, numbers, underscores, and dots. No spaces, uppercase letters, or special characters like hyphens. For example, img_hero.png is okay, but Img Hero.png is not.
If you’re still stuck...
Check the Logcat tab for the full error message (look for ResourceNotFoundException). It’ll tell you exactly which resource can’t be found, which helps narrow down the issue even more.
内容的提问来源于stack exchange,提问作者Nanda Febrian A

