XML 根布局設置 android:background="#ffffff",但圖片加載過程中背景顯示為黑色。
圖片異步加載庫(如 Universal Image Loader、Glide 早期版本)在佔位符階段使用 DownloadedDrawable,其構造函數默認背景為黑色:
// 庫內部代碼示例
public class DownloadedDrawable extends ColorDrawable {
public DownloadedDrawable(...) {
super(Color.BLACK); // 這裡硬編碼黑色背景
...
}
}
調用 imageView.setImageDrawable(downloadedDrawable) 時,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);
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();
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@color/white</item>
<item name="colorBackground">@color/white</item>
</style>
android:background vs android:foreground (API 23+):前者在內容後,後者在內容前,點擊波紋用 foreground。異步圖片加載佔位符背景色不匹配是常見視覺Bug,設置 ImageView 自身背景或配置庫佔位符 API 即可徹底解決。