-1

我正在从 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);


}
4

1 回答 1

0

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

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

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

于 2013-05-01T13:57:01.663 回答