目前我正在使用它来下载并在我的 recyclerview 中显示图像:
private class RetrieveImageTask extends AsyncTask<URL,Void,Drawable>{
URL url;
InputStream inputStream;
protected Drawable doInBackground(URL... urls){
url = urls[0];
try {
inputStream = (InputStream)url.getContent();
} catch (IOException e) {
e.printStackTrace();
}
return Drawable.createFromStream(inputStream, null);
}
protected void onPostExecute(Drawable drawable) {
}
}
然后我在 RecyclerViewAdapter 的 onBindViewHolder
中使用这个类:
@Override
public void onBindViewHolder(ItemViewHolder item, int i) {
try {
item.title.setText(aushangdata.getJSONObject(i).getString("title"));
item.desc.setText(aushangdata.getJSONObject(i).getString("text"));
item.tag.setText(aushangdata.getJSONObject(i).getString("category"));
item.link.setText(aushangdata.getJSONObject(i).getString("link"));
URL myUrl = new URL(aushangdata.getJSONObject(i).getString("image"));
RetrieveImageTask task = new RetrieveImageTask();
Drawable drawable = task.execute(myUrl).get();
item.thumb.setImageDrawable(drawable);
} catch (JSONException | IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
这显然是一个非常糟糕的解决方案,而且非常明显:当我打开包含 recyclerview 的 fragment 时,我有长达 0.5 秒的延迟,当我快速向下滚动时它也有延迟,因为图像占用了卡片上有很多空间。
我的问题是:在 RecyclerView
中下载和显示图像的最佳方式是什么?
最佳答案
您可以使用 Glide:https://github.com/bumptech/glide
使用起来也很简单:
Glide.with(CONTEXT).load(URL or DRAWABLE).asBitmap().into(IMAGEVIEW);
查看 wiki 以获取更多选项:https://github.com/bumptech/glide/wiki
在您的代码中:
Glide.with(context).load(myUrl).asBitmap().into(item.thumb);
希望对您有所帮助。
关于java - 在recyclerview中高效下载和使用图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076032/