我从网址抓取图片。我使用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);
}
答案 0 :(得分:0)
另一个简单的选项,虽然根据您的列表大小,内存成本很高,但是在加载图片调用ImageView
后view.setTag(bitmap)
上,并且在您尝试获取图片之前,请做一个理智的选择检查。
if(view.getTag() != null) {
view.setImageBitmap((Bitmap)view.getTag());
} else {
new ImageLoader().execute(view, +URL+listArrphoto[position]);
}
当然,我会选择下载到应用程序缓存目录并从文件加载(如果存在)。