前段时间项目让调ui,所有图片的默认图统一,但是大大小小的图片有好多,来回改比较麻烦。所以把我的思路在这里记一下。
主要实现方式就是利用layer-list
small_image.xml
<?xml version="1.0" encoding="utf-8"?>
<level-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/small_image_failed" android:maxLevel="0" />
<item android:drawable="@color/image_loading_bg" android:maxLevel="1" />
</level-list>
small_image_failed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/image_loading_bg" />
</shape>
</item>
<item>
<bitmap android:gravity="center" android:src="@drawable/logo" />
</item>
</layer-list>
然后设置给对应的imageview就ok了
image_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
<ImageView
android:background="@drawable/small_image"
android:scaleType="centerCrop"
android:layout_width="100dp"
android:layout_height="50dp" />
<ImageView
android:background="@drawable/small_image"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_marginTop="10dp"
android:scaleType="fitXY" />
<ImageView
android:background="@drawable/small_image"
android:scaleType="centerCrop"
android:layout_width="300dp"
android:layout_marginTop="10dp"
android:layout_height="150dp" />
<ImageView
android:background="@drawable/small_image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="10dp"
android:scaleType="fitXY" />
</LinearLayout>
这里要说明一下,如果给imageview设置了scaleType就会影响图片的加载方式(src),当然默认图也会影响,而且一般的图片加载框架都是默认设置src,所以想要默认图的大小尺寸不变但同时可能给加载后的图片设置加载方式,最好是把默认图设置成background。一般的图片加载控件有提供加载默认图片的方案,但一样在上面的case中,就会出现默认图拉伸。这种方案适用于默认图片相同,背景颜色相同,但是imageview大小不同的情况,大家视情况而定。
效果如下: