Android:Button设置图片后布局可见但运行时不显示问题求助
Hey there! I’ve run into this exact frustrating issue before—where your Button’s image looks perfect in Android Studio’s layout preview, but poofs into thin air when you launch the app. Let’s break down the most likely fixes to get that image showing up for real:
1. Check Drawable Resource Compatibility
If you’re using a VectorDrawable (those XML-based scalable images), older Android versions might not load it properly by default. Here’s how to fix that:
- Make sure your vector drawable is stored in the general
drawablefolder (not a version-specific one likedrawable-v24). - In your app-level
build.gradlefile, add this to thedefaultConfigblock:android { defaultConfig { vectorDrawables.useSupportLibrary = true } } - In your
AppCompatActivity’sonCreatemethod, enable vector support:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); setContentView(R.layout.your_activity_layout); }
2. Verify Your Button’s Image Property
Your code snippet cuts off at android:foregro—if you were using android:foreground, that can behave unpredictably on some devices or themes. Swap it out for a more reliable drawable placement attribute instead:
- Use
android:drawableTop,android:drawableLeft,android:drawableStart, etc., depending on where you want the image. - For example, here’s an updated Button using
drawableTop:<androidx.appcompat.widget.AppCompatButton android:id="@+id/button_intro" android:layout_width="70dp" android:layout_height="70dp" android:layout_margin="8dp" android:background="@drawable/round_button" android:drawableTop="@drawable/your_target_image" android:padding="8dp" /> - Pro tip: Use
AppCompatButtoninstead of the defaultButtonto avoid theme-related conflicts with custom attributes.
3. Clear Android Studio’s Caches
Sometimes the preview and actual app get out of sync due to cached data. Try these steps:
- Go to
Build > Clean Project - Then
Build > Rebuild Project - If that doesn’t work, go to
File > Invalidate Caches... > Invalidate and Restart
4. Check for Theme Conflicts
If your app uses a Material Design theme, it might override some Button properties. Ensure your theme doesn’t disable drawables for buttons, and using AppCompatButton (as mentioned earlier) will help bypass most theme-related issues.
Give these steps a try—one of them should get that image showing up when you run the app!
内容的提问来源于stack exchange,提问作者Ved Sarkar

