Android viewHolder处理listView滑动

在没有用viewHolder的情况下,listView表现效率低下。如果加载的数量过多则会一点点的消耗内存,直到抛出oom。开始异步加载图片会出现图片错位的问题,后来查阅资料将holder里边的图片地址和图片一一对应起来,在异步加载的回调函数中将其替换回来。

holder.thumb_image.setTag(hotel.getHotelTitlePic());  //避免图标错位,在异步加载成功后替换回来

ImageView imageView = (ImageView) listView.findViewWithTag(imageUrl);
       if(imageView != null){
       imageView.setImageDrawable(imageDrawable);
       imageView.setTag("");
       }
以上关键代码解决图片错位问题。

下面是getView()方法

public View getView(int position, View rowView, ViewGroup parent){
final MHotelInfo hotel = this.getItem(position);
if (rowView == null) {
holder = new ViewHolder();
LayoutInflater inflater = ((Activity) this.getContext())
.getLayoutInflater();
rowView = inflater.inflate(R.layout.hotel_item_view, null);

holder.typeName = (TextView) rowView.findViewById(R.id.hotelType);

      holder.thumb_image=(ImageView)rowView.findViewById(R.id.img);// 缩略图  
      holder.distance = (TextView) rowView.findViewById(R.id.distance);

      rowView.setTag(holder);
}else{
holder = (ViewHolder) rowView.getTag();
}

      // 设置ListView的相关值  
      holder.thumb_image.setTag(hotel.getHotelTitlePic());  //避免图标错位,在异步加载成功后替换回来
      holder.typeName.setText(hotel.getTypeName());

      if(null == hotel.getHotelTitlePic() || hotel.getHotelTitlePic().equals("")){  //如果没有图标就显示默认图标
       holder.thumb_image.setImageResource(R.drawable.downloadfalse);
      }else{
       //异步加载图片
       imageLoader.loadDrawable(hotel.getHotelTitlePic(), new ImageCallback() {
       public void imageLoaded(Drawable imageDrawable, String imageUrl) {
       ImageView imageView = (ImageView) listView.findViewWithTag(imageUrl);
       if(imageView != null){
       imageView.setImageDrawable(imageDrawable);
       imageView.setTag("");
       }
       }
       });
      }

return rowView;
}

static class ViewHolder {
       TextView typeName;
       ImageView thumb_image;
       }  


你可能感兴趣的:(android,viewholder)