2016-09-19 59 views
3

我正在使用RecyclerView和GridLayoutManager。對於網格中的每個項目,我需要調用REST API來檢索數據。然後,在從遠程獲取數據之後,我使用UIL加載/顯示圖像。RecyclerView onBindViewHolder對於一個單元格被調用的次數太多

一切似乎都很好。但我發現onBindViewHolder被稱爲對於特定項目太多太多次。

logcat log

談話是便宜,讓我告訴你的代碼:

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { 
    EditCourseImageAttachmentHolder holder = (EditCourseImageAttachmentHolder) viewHolder; 
    holder.itemView.setLayoutParams(getLayoutParams(position)); 
    holder.attachmentView.initData(dataSource.get(headerView == null ? position : position - 1), urlMap); 
} 
public static class EditCourseImageAttachmentHolder extends RecyclerView.ViewHolder { 

    public final AttachmentView attachmentView; 

    public EditCourseImageAttachmentHolder(AttachmentView itemView) { 
     super(itemView); 
     this.attachmentView = itemView; 
    } 
} 

----------- --------- AttachmentView.Java --------

@Override 
protected void onAttachedToWindow() { 
    super.onAttachedToWindow(); 
    subscription = tryLoadLocalImage(data) 
      .subscribeOn(Schedulers.io()) 
      .flatMap(new Func1<String, Observable<String>>() { 
       @Override 
       public Observable<String> call(String localImageUrl) { 
        if (StringUtils.isNotBlank(localImageUrl)) { 
         return Observable.just(localImageUrl); 
        } 
        if (urlMap.containsKey(data.getUid())) { 
         return Observable.just(urlMap.get(data.getUid())); 
        } else { 
         //Remote API call 
         String qiNiuUrl = getQiNiuUrl(data); 
         urlMap.put(data.getUid(), qiNiuUrl); 
         return Observable.just(qiNiuUrl); 
        } 
       } 
      }) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(new Action1<String>() { 
       @Override 
       public void call(String localImageUrl) { 
        showImage(localImageUrl); 
       } 
      }, new Action1<Throwable>() { 
       @Override 
       public void call(Throwable throwable) { 
       } 
      }); 
} 

@Override 
protected void onDetachedFromWindow() { 
    super.onDetachedFromWindow(); 
    if (subscription != null && subscription.isUnsubscribed()) { 
     subscription.unsubscribe(); 
    } 
} 

回答

0

根本原因是我改變了ItemView的LayoutParam ....

它在我刪除這些代碼後效果很好。 但是,很奇怪,只有特定位置的物品纔會重新綁定。

0
if (subscription != null && !subscription.isUnsubscribed()) { 
    subscription.unsubscribe(); 
} 

你的代碼應該是這樣的......

相關問題