我有一个 ListView,其中包含一些文本和一个 ImageView 的项目。我想使用 AsyncTask 来加载 ImageView(延迟加载)。我知道有一些图书馆可以做到这一点。问题是无法仅使用 URL 获取图像,例如
imageLoader.displayImage(imageUri, imageView);
因为我需要向 HTTP GET(身份验证令牌)添加一些标头。因此,在适配器的 getView() 中,我必须启动一个 AsyncTask,它将图像下载为位图并将其显示在 ImageView 上。
有代码示例吗?我尝试在 AsyncTask 的构造函数中将 ImageView 传递给 AsyncTask,下载 Bitmap 并将其分配给 onPostExecute 上的 ImageView,如下所示:
public class LoadImageTask extends AsyncTask<String, Void, Bitmap>{
private ImageView mImage;
private Context mContext;
private String imageId;
private Throwable mThrown = null;
public LoadImageTask(ImageView ivImage, Context context) {
mImage = ivImage;
mContext = context;
}
@Override
protected Bitmap doInBackground(String... params) {
imageId = params[0];
// Build request and request token
....
//Process the response
try {
HttpEntity entity = mHttpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedInputStream bis = new BufferedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
inputStream.close();
return bm;
} catch (IOException e) {
mThrown = e;
RestClient.consumeContent(mHttpResponse);
return null;
}
}
RestClient.consumeContent(mHttpResponse);
return null;
}
@Override
protected void onPostExecute(Bitmap bm) {
mImage.setImageBitmap(bm);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.news_item, null);
TextView tvNewsTitle = (TextView) rowView.findViewById(R.id.tvNewsTitle);
TextView tvUpdateDate = (TextView) rowView.findViewById(R.id.tvUpdateDate);
ImageView ivImage = (ImageView) rowView.findViewById(R.id.ivNewsThumbnail);
News news = mNewsList.get(position);
tvNewsTitle.setText(news.getTitle());
tvUpdateDate.setText(news.getLastUpdate());
new LoadImageTask(ivImage, mContext).execute(news.getImageThumbnail());
return rowView;
}
但看起来它总是只更新 ListView 的第一个元素。
有没有示例代码?