【问题标题】:Image is loading every time in AsyncTask每次在 AsyncTask 中加载图像
【发布时间】: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


【解决方案1】:

另一个简单的选择是在加载图像调用 view.setTag(bitmap) 之后在您的 ImageView 上,但在尝试获取图像之前,请进行完整性检查,但根据您的列表大小可能会消耗大量内存。

p>
if(view.getTag() != null) {
    view.setImageBitmap((Bitmap)view.getTag());
} else {
    new ImageLoader().execute(view, +URL+listArrphoto[position]);
}

当然,我会选择下载到应用程序缓存目录并从文件中加载(如果存在)。

【讨论】:

  • 您也可以尝试将其存储到 Map 中,其中键是 url,值是位图。同样,对于大型列表,我不建议这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 2018-06-28
相关资源
最近更新 更多