可以根据url地址来加载图片,并缓存。
public class AsyncImageLoader {
final Handler handler = new Handler(Looper.getMainLooper());
private HashMap<String, SoftReference<Drawable>> imageCache;
String title; //图片对应的标题
public AsyncImageLoader() {
imageCache = new HashMap<>();//图片缓存
}
// 回调函数
public interface ImageCallback {
void onImageLoad(Integer t, String title, Drawable drawable);
void onError(Integer t);
}
public void loadDrawable(final Integer pos, final String imageUrl, String title,
final ImageCallback imageCallback) {
this.title = title;
new Thread() {
@Override
public void run() {
LoadImg(pos, imageUrl, imageCallback);
}
}.start();
}
public void LoadImg(final Integer pos, final String imageUrl,
final ImageCallback imageCallback) {
// 首先判断是否在缓存中
// 但有个问题是:ImageCache可能会越来越大,以至用户内存用光,所以要用SoftReference(弱引用)来实现
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
final Drawable drawable = softReference.get();
if (drawable != null) {
handler.post(new Runnable() {
@Override
public void run() {
imageCallback.onImageLoad(pos, title, drawable);
}
});
return;
}
}
// 尝试从URL中加载
try {
final Drawable drawable = loadImageFromUrl(imageUrl);
if (drawable != null) {
imageCache.put(imageUrl, new SoftReference<>(drawable));
}
handler.post(new Runnable() {
@Override
public void run() {
imageCallback.onImageLoad(pos, title, drawable);
}
});
} catch (IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
imageCallback.onError(pos);
}
});
e.printStackTrace();
}
}
// 根据URL加载图片,如果出现错误throws IOException式的错误,以便在LoadImg中捕获,执行OnError()函数
public static Drawable loadImageFromUrl(String url) throws IOException {
URL m;
InputStream i;
m = new URL(url);
i = (InputStream) m.getContent();
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
}
使用:
new AsyncImageLoader().loadDrawable(i, url,title, new AsyncImageLoader.ImageCallback() {
@Override
public synchronized void onImageLoad(Integer t,String title,Drawable drawable) {
images.add(drawable);
titles.add(title);
adapter.notifyDataSetChanged();
}
@Override
public void onError(Integer t) {
Toast.makeText(MainActivity.this,"图片加载失败",Toast.LENGTH_SHORT).show();
}
});