首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Activity 背景色設置為白色無效:被 DownloadedDrawable 黑色背景覆蓋

     編輯:程式設計綜合問答

問題現象

XML 根布局設置 android:background="#ffffff",但圖片加載過程中背景顯示為黑色。

根本原因

圖片異步加載庫(如 Universal Image Loader、Glide 早期版本)在佔位符階段使用 DownloadedDrawable,其構造函數默認背景為黑色:

// 庫內部代碼示例
public class DownloadedDrawable extends ColorDrawable {
    public DownloadedDrawable(...) {
        super(Color.BLACK); // 這裡硬編碼黑色背景
        ...
    }
}

調用 imageView.setImageDrawable(downloadedDrawable) 時,ImageView 背景變黑,覆蓋了父佈局的白色。

解決方案

1. 設置 ImageView 自身背景為白色(最直接)

<ImageView
    android:id="@+id/imageView"
    android:background="#ffffff"  <!-- 關鍵:設置 View 自身背景 -->
    android:scaleType="centerCrop"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

或代碼:imageView.setBackgroundColor(Color.WHITE);

2. 使用加載庫的佔位符 API 替換默認 Drawable

Glide:

Glide.with(this)
    .load(url)
    .placeholder(R.drawable.placeholder_white) // 白色佔位圖
    .error(R.drawable.error_white)
    .into(imageView);

Universal Image Loader:

DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showImageOnLoading(new ColorDrawable(Color.WHITE)) // 白色佔位
    .showImageForEmptyUri(new ColorDrawable(Color.WHITE))
    .showImageOnFail(new ColorDrawable(Color.WHITE))
    .build();

3. XML 主題層面統一背景

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@color/white</item>
    <item name="colorBackground">@color/white</item>
</style>

避坑清單

  • 父佈局背景 不會 透傳給子 View 的背景繪製區域,子 View 需自行設置背景或透明。
  • android:background vs android:foreground (API 23+):前者在內容後,後者在內容前,點擊波紋用 foreground。
  • 圖片加載庫默認佔位符多為灰/黑,務必顯式設置白色佔位符匹配設計稿。

異步圖片加載佔位符背景色不匹配是常見視覺Bug,設置 ImageView 自身背景或配置庫佔位符 API 即可徹底解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved