在重复使用View时,防止ListView一次又一次地下载图像

时间:2014-05-31 08:23:19

标签: android image listview android-listview

我已尝试过网络中的其他所有示例,但似乎无法解决此问题。我有一个带有一个ImageView和一个TextView的ListView。图像以异步方式加载到ImageView中。但由于android似乎重用了Views,因此经常调用getView()并且一次又一次地下载相同的图像。所以我尝试使用ViewHolder。代码如下:

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {

        LayoutInflater inflater = (LayoutInflater) this.mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_view_item, null);

        holder = new ViewHolder();
        holder.imageDesc = (TextView) convertView.findViewById(R.id.desc);
        holder.image = (ImageView) convertView.findViewById(R.id.image);

        convertView.setTag(holder);

            holder.imageDesc.setTypeface(null, Typeface.BOLD);
        holder.imageDesc.setText(dataList.get(position).getImageDesc());

            //Loads image asynchronously into the imageView
            ImageLoader.loadImage(holder.image, ((ListViewItem)getItem(position)).getImageLink());

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

static class ViewHolder {
    TextView imageDesc;
    ImageView image;

}

这似乎只下载一次代码。但是,如果我滚动ListView,项目将随机放置并显示在ListView中。 没有这些问题,在ListView中异步显示图像的正确方法是什么?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

使用此:

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) this.mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_view_item, null);

            holder = new ViewHolder();
            holder.imageDesc = (TextView) convertView.findViewById(R.id.desc);
            holder.image = (ImageView) convertView.findViewById(R.id.image);

            convertView.setTag(holder);
                } else {
            holder = (ViewHolder) convertView.getTag();
        }
     holder.imageDesc.setTypeface(null, Typeface.BOLD);
            holder.imageDesc.setText(dataList.get(position).getImageDesc());

                //Loads image asynchronously into the imageView
                ImageLoader.loadImage(holder.image, ((ListViewItem)getItem(position)).getImageLink());
        return convertView;
    }