You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:Button设置图片后布局可见但运行时不显示问题求助

Fix: Button Image Shows in Preview but Disappears on App Run

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 drawable folder (not a version-specific one like drawable-v24).
  • In your app-level build.gradle file, add this to the defaultConfig block:
    android {
        defaultConfig {
            vectorDrawables.useSupportLibrary = true
        }
    }
    
  • In your AppCompatActivity’s onCreate method, 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 AppCompatButton instead of the default Button to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:53:07