ListView回收问题

时间:2014-10-15 18:09:36

标签: android listview android-asynctask imageview

我有自定义适配器的列表视图,每行都有一个imageview,我通过URL将图像下载到AsyncTask,从远程服务器下载图像。我的代码正在运行,但是当我滚动列表视图时,会再次下载ImageViews的下载图像。

我想下载第一次创建listview的图片。我研究了很多主题,但我对此一无所知。我该怎么办?

我的自定义适配器位于...

之下
public ListAdapter(Context context, ProgramInfo values) {

        this.context = context;
        this.values = values;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      }

       @Override
       public int getCount(){

           return values.getSize();
            }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

            View rowView = mInflater.inflate(R.layout.list_row, null);
            TextView programName = (TextView)rowView.findViewById(R.id.programName);
            TextView programTime = (TextView)rowView.findViewById(R.id.programTime);
            TextView programState = (TextView)rowView.findViewById(R.id.programState);
            ImageView programImage = (ImageView)rowView.findViewById(R.id.programImage);


            programName.setText(values.programNames.get(position));
            programTime.setText(values.programTimes.get(position));


            new DownloadImage(programImage).execute(values.programImageUrls.get(position)); // download images


        return rowView;

    }

我的AsyncTask ......

private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
     ImageView bmImage;

     public DownloadImage(ImageView bmImage) {
         this.bmImage = bmImage;
     }

     protected Bitmap doInBackground(String... urls) {
         String urldisplay = urls[0];
         Bitmap mIcon11 = null;
         try {
             HttpURLConnection urlConnection = (HttpURLConnection)new URL(urldisplay).openConnection();
             urlConnection.setDoInput(true);
             InputStream in = urlConnection.getInputStream();
             mIcon11 = BitmapFactory.decodeStream(in);
             urlConnection.disconnect();
         } catch (Exception e) {
             Log.e("Error", e.getMessage());
             e.printStackTrace();
         }
         return mIcon11;
     }

     protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
        } 
     }

...谢谢

1 个答案:

答案 0 :(得分:1)

在适配器中,对于每个出现的新行,将执行 getView 中的所有操作 所以你必须在 getView 中使用 ViewHolder 来保存每行的元素状态 和我们if语句在重新下载之前检查ImageView是否为null .... 这就是我所说的一个惊人的例子......

Asynchronous Image Loader In Android ListView