android gui 开发 listiew中如何加载图片?
在listview中每一条都有一个图片,需要从网络请求,现在我实现的方式经常很卡,并且加载的很慢,大家在listiew中如何加载图片?
べ悠然飘过べ
12 years ago
Answers
一般都使它吧:
public class AsyncImageLoader {
public Map<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loaDrawable(final String imageUrl,
final ImageCallBack imageCallBack) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (null != drawable) {
return drawable;
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageCallBack.imageLoaded((Drawable) message.obj);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public Drawable loadImageFromUrl(String url) {
URL tempUrl;
InputStream inputStream = null;
Drawable drawable = null;
try {
tempUrl = new URL(url);
inputStream = (InputStream) tempUrl.getContent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
drawable = Drawable.createFromStream(inputStream, "src");
} catch (OutOfMemoryError err) {
}
return drawable;
}
public interface ImageCallBack {
public void imageLoaded(Drawable imageDrawable);
}
}
馒头【伪】
answered 12 years ago