【发布时间】:2013-05-01 13:49:14
【问题描述】:
我正在从 URL 获取图像。我使用 AsyncTask 来显示图像。但是每次我上下滚动时都会重新加载图像。
这是我的代码。
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.useryouramourstlist, null,
true);
final ImageView userprofilepic = (ImageView) view
.findViewById(R.id.userprofilepic);
try
{
new ImageLoader().execute(view, +URL+listArrphoto[position]);
}
catch(Exception e)
{
}
return view;
}
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private View view;
private Bitmap bm = null;
@Override
protected Bitmap doInBackground(Object... parameters) {
// Get the passed arguments here
view = (View) parameters[0];
String uri = (String)parameters[1];
bm = loadImageFromUrl(uri);
return bm;
//return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && view != null) {
ImageView albumArt = (ImageView) view.findViewById(R.id.userprofilepic);
albumArt.setImageBitmap(bitmap);
}
}
}
public static Bitmap loadImageFromUrl(String url) {
Bitmap bm;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = null;
try
{
is= conn.getInputStream();
}catch(IOException e)
{
return null;
}
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
return null;
}
return Bitmap.createScaledBitmap(bm,60,60,true);
}
【问题讨论】:
-
如果想避免每次都下载,您需要缓存图像。使用通用图像加载器的 LazyList。检查链接stackoverflow.com/questions/15621936/whats-lazylist
-
但是为什么每次上下滚动时都会加载图像。如果我在没有 AsyncTask 的情况下使用,那么向上或向下滚动时它不会一次又一次地加载
-
您可能在 getview 中调用 asynctask。
-
你能告诉我怎么做吗?
-
如何使用惰性列表或 UIL 检查第一条评论中的链接。它将图像缓存在 sccard 或手机内存中。如果已经存在,则从缓存中显示,否则下载缓存并显示
标签: android android-layout android-asynctask