Android Async loading Images in Listview - images are blinking

落花浮王杯 提交于 2019-12-24 16:12:19

问题


I have been struggling with asynchronously loading images in ListView, because while they're loading, some of them are blinking (they're are replaced by another loaded image) and some of them are showed in wrong items.

Class for downloading images:

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

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

  protected Bitmap doInBackground(String... urls) 
  {
      String urldisplay = urls[0];
      Bitmap mIcon11 = null;

      try 
      {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
      } 
      catch (Exception e) {}

      return mIcon11;
  }

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

Calls for each item, when I am assigning data to ListView:

ImageView image = (ImageView)view.findViewById(R.id.imageView);
TextView title = (TextView)view.findViewById(R.id.txtTitle);

new DownloadImageTask(image).execute(data.image);
title.setText(data.title);

What should I do differently?


回答1:


In addition to what Forin has said, there are many libraries that really help out on things like this. My personal favorite at the moment is AQuery:

https://code.google.com/p/android-query/

Let's say you have an ImageView and you want to download an image and set the imageView to hold that image. Sounds sort of difficult, right? With AQuery this is done in one line:

aq.id(R.id.name_of_image_view).image("http://url-of-image.com/image.png");

aq in this case is an AQuery object declared like so:

AQuery aq = new AQuery();



回答2:


Firstly, you should reconsider using this library:

https://github.com/nostra13/Android-Universal-Image-Loader

It will help you downloading images and displaying them in ListView.

Your problem is connected with recycling views in ListView. So your ImageView in getView() is reused, that's why positions in your list are changing. If you are using holder and have something like holder.image.setImageDrawable(...) inside if/else statement, you should move it outside condition, just above return.



来源:https://stackoverflow.com/questions/26266295/android-async-loading-images-in-listview-images-are-blinking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!