Android:在listview中加载Imageview时不要重新加载

时间:2013-08-20 14:59:36

标签: android android-listview android-imageview

我想对此行为做一点解释:

我创建了一个列表视图。列表视图的每个项目都有一个图像视图,其中填充了URL中的图像。

当我向下滚动到列表时,当项目出现时加载每个图像=>行

但是,当我向上滚动时,会再次下载先前加载的图像。

如何阻止此行为?

以下是我的下载程序的代码:

public 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) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

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

这是我的适配器的一段代码:

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

        Activity activity = (Activity) getContext();

        LayoutInflater inflater = activity.getLayoutInflater();

        View rowView;
        ArticleHome article = getItem(position);


        if (position == 0) {
            rowView = inflater.inflate(R.layout.item_ligne_home_premier, null);
            new DownloadImageTask((ImageView) rowView.findViewById(R.id.imgimg)).execute(article.getImage());
            TextView textView = (TextView) rowView.findViewById(R.id.titlenew);
            textView.setText(article.getTitle());
            textView.setTypeface(faceLight);
        }
        else {
            rowView = inflater.inflate(R.layout.item_ligne_home, null);
            new DownloadImageTask((ImageView) rowView.findViewById(R.id.imgimg)).execute(article.getImage());
            TextView title = (TextView) rowView.findViewById(R.id.titlearticleothers);
            title.setText(article.getTitle());
            title.setTypeface(faceBold);
            TextView desc = (TextView) rowView.findViewById(R.id.descriptionarticleothers);
            // Add test si < a une certaine longeuryr
            desc.setText(article.getDescription().substring(0, 100));
            desc.setTypeface(faceLight);
        }


//      img.setImageAlpha(1680);
//      img.setImageAlpha(1880); // Pasmal plus haut plus foncé


        return rowView;

    } 

1 个答案:

答案 0 :(得分:0)

实际操作的方法是缓存下载的每个图像,并使用Cache中的图像更新ListView项目,并且只有在缓存中不存在图像时才下载。

这将避免下载。

通过Pramod J George检查此答案,尤其是ImageLoader类。