Android viewHolder處理listView滑動

在沒有用viewHolder的情況下,listView表現效率低下。如果加載的數量過多則會一點點的消耗內存,直到拋出oom。開始異步加載圖片會出現圖片錯位的問題,後來查閱資料將holder裏邊的圖片地址和圖片一一對應起來,在異步加載的回調函數中將其替換回來。

holder.thumb_p_w_picpath.setTag(hotel.getHotelTitlePic());  //避免圖標錯位,在異步加載成功後替換回來

ImageView p_w_picpathView = (ImageView) listView.findViewWithTag(p_w_picpathUrl);
       if(p_w_picpathView != null){
       p_w_picpathView.setImageDrawable(p_w_picpathDrawable);
       p_w_picpathView.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_p_w_picpath=(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_p_w_picpath.setTag(hotel.getHotelTitlePic());  //避免圖標錯位,在異步加載成功後替換回來
      holder.typeName.setText(hotel.getTypeName());

      if(null == hotel.getHotelTitlePic() || hotel.getHotelTitlePic().equals("")){  //如果沒有圖標就顯示默認圖標
       holder.thumb_p_w_picpath.setImageResource(R.drawable.downloadfalse);
      }else{
       //異步加載圖片
       p_w_picpathLoader.loadDrawable(hotel.getHotelTitlePic(), new ImageCallback() {
       public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl) {
       ImageView p_w_picpathView = (ImageView) listView.findViewWithTag(p_w_picpathUrl);
       if(p_w_picpathView != null){
       p_w_picpathView.setImageDrawable(p_w_picpathDrawable);
       p_w_picpathView.setTag("");
       }
       }
       });
      }

return rowView;
}

static class ViewHolder {
       TextView typeName;
       ImageView thumb_p_w_picpath;
       }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章