我有一个自定义listview
,其中包含来自服务器的图像和文本。如果服务器返回 500 多组数据,我可以将所有数据呈现给我listview
,但加载需要很长时间
相反,当列表向下滚动时,我应该呈现数据。为此,我返回了一些代码来加载图像,但我仍然对这段代码不满意。我getView()
通过调用 manager.fetchBitMapThread(data.getImgUrl(),iv)
(ImageLoaderThread)从该方法加载图像。因为运行时会创建这么多线程。有人可以建议加载自定义数据的好主意吗listview
?
我见过OnScrollListener
,但我不明白如何为自定义实现这一点listview
。
manager.fetchBitMapThread(data.getImgUrl(),iv);
public class Manager {
ImageView imageView;
final int stub_id=R.drawable.stub;
private final Map<String, Bitmap> bitMap;
public Manager() {
bitMap = new HashMap<String, Bitmap>();
}
public void fetchBitMapThread(final String urlString, final ImageView imageView) {
this.imageView = imageView;
if (bitMap.containsKey(urlString)) {
imageView.setImageBitmap(bitMap.get(urlString));
}
imageView.setImageResource(stub_id);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
if(!message.equals(null))
imageView.setImageBitmap((Bitmap) message.obj);
else
imageView.setImageResource(stub_id);
}
};
Thread thread = new Thread() {
@Override
public void run() {
// set imageView to a "pending" image
Bitmap bitM = fetchBitmap(urlString);
Message message = handler.obtainMessage(1, bitM);
handler.sendMessage(message);
}
};
thread.start();
}
public Bitmap fetchBitmap(String urlString) {
if (bitMap.containsKey(urlString)) {
return bitMap.get(urlString);
}
Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Bitmap drawable = BitmapFactory.decodeStream(is);
if (drawable != null) {
bitMap.put(urlString, drawable);
//Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", " + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", " + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
} else {
//wrong.setImageResource(stub_id);
Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
}
return drawable;
} catch (MalformedURLException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
//imageView.setImageResource(stub_id);
return null;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
// imageView.setImageResource(stub_id);
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}