Android Studio Kotlin中ImageView仅显示空白方块问题求助
Hey there, let's walk through the most likely fixes for your ImageView showing a white square instead of your calc image:
1. Use android:src (or app:srcCompat) instead of android:background
This is the most common mistake here! When you use android:background, the image is treated as a background that stretches to fit the View's size (which might be zero or tiny if you're using wrap_content without a proper content source). Instead, use android:src to load the image as the ImageView's content—this will make wrap_content correctly adjust to the image's actual dimensions.
Here's the corrected ImageView code snippet:
<ImageView android:id="@+id/calcImg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/calc" <!-- Changed from background to src --> android:contentDescription="Calculator icon" <!-- Added a meaningful description for accessibility --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/appName" app:layout_constraintHorizontal_bias="0.51" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/>
If you're using vector drawables or need better backward compatibility, use app:srcCompat="@drawable/calc" instead (just make sure you have vectorDrawables.useSupportLibrary = true in your app-level build.gradle).
2. Verify Your Image Resource
Double-check these details about your calc image:
- It's placed in the correct
res/drawablefolder (or density-specific folders likedrawable-mdpi,drawable-hdpifor optimized display across devices). - The filename is all lowercase with no spaces or special characters (Android doesn't allow uppercase letters or symbols in resource filenames).
- The image format is supported (PNG, JPG, WebP, or vector drawables—avoid formats like BMP which may cause loading issues).
3. Check for Layout Constraints Conflicts
While less likely, if the ImageView's constraints are forcing it to a tiny size, you might only see a sliver (or white square if the background is set). Using android:src should fix the wrap_content sizing, but you can also temporarily set fixed width/height (like android:layout_width="100dp" android:layout_height="100dp") to test if the image loads at all.
Give these steps a try—most of the time switching from background to src resolves this exact issue!
内容的提问来源于stack exchange,提问作者Sushil

