现在一般加载网络图片都是用的ImageLoader来做,而且功能是越来越强大,部分ImageLoader已经改得可以增加载入中及载入失败的时候显示的图片了,非常的实用。这里主要是给大家介绍一个非常简单的小技巧,自己实现当图片没有加载出来的时候,将ImageView添加文字提示。
第一种方法:使用Button替换ImageView。
这种方法局限性比较大,在个别只使用background而不需要用src的情况下可以选用。因为Button可以设置文字,所以只需要在未加载之前设置文字,加载完成后去掉文字即可。
第二种方法:自定义ImageView。
实际项目中,遇到的需求总是五花八门的,你总有这样那样的理由无法使用现存的各种看上去优越的方法。那不妨简单地重写一下ImageView。
那么怎么重写法呢?按我们的设想,是希望能在加载完成图片之前,给ImageView画上一段文字提示,譬如“正在加载”。那么理所应当是改写ImageView的onDraw()方法。我们先来看看ImageView的onDraw()都干了什么。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawable == null) {
return; // couldn't resolve the URI
}
<span style="white-space:pre"> </span>//省略。。。。
}
看到这里就有种喜出望外的感觉了,在onDraw()里就有判断mDrawable是否为null的语句。在源码中是直接return,那我们在这里稍作修改画上文字就可以了~下面贴出代码。
public class ImageViewWithText extends ImageView {
Paint textPaint;
String tips = "正在加载";
Context context;
public ImageViewWithText(Context context) {
super(context);
this.context = context;
}
public ImageViewWithText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initPaint(context);
}
public ImageViewWithText(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
}
private void initPaint(Context mContext) {
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
if (getDrawable() == null) {
textPaint.setTextSize(context.getResources().getDimensionPixelSize(
R.dimen.app_load_textsize));
canvas.drawText(tips, getWidth() / 2 - textPaint.measureText(tips)
/ 2, getHeight() / 2, textPaint);
}
super.onDraw(canvas);
}
}
关键代码就是直接在super.onDraw()之前把要的文字(或者bitmap)画出来即可~那么在该ImageView没有drawable(还没加载好网络图片等情况)时就会显示文字提示了~