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("");
        }
以上關鍵代碼解決圖片錯位問題。 this

下面是getView()方法 spa

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;
        }   設計

可是ViewHolder爲何是被設計成static類型的,本人一直沒弄清楚。在網上找了些資料可是一直沒能看到一個能說服個人理由。又說節省內存,保持對象的惟一性,還有說保持圖片不錯亂可是我的感受都不怎麼靠譜。今天我試了下將static去掉照常運行沒感受和之前有什麼區別。後來我查了下static類的一些特性,首先ViewHolder是一個內部類如果static類的話則不須要依賴外部類的對象。也就是說只有static的內部類的成員變量才能夠被聲明成static類型,若內部類不是static類型的則不能夠聲明靜態成員變量。不知道是否是static內部類的這個特性吸引了設計者?若是有誰清楚這個問題還請不吝賜教。 對象

相關文章
相關標籤/搜索