对于一个单元格,RecyclerView onBindViewHolder被调用太多次

时间:2016-09-19 12:33:07

标签: android android-recyclerview

我正在使用RecyclerView和GridLayoutManager。对于网格中的每个项目,我需要调用REST api来检索数据。然后,在从远程异步获取数据后,我使用UIL加载/显示图像。

一切似乎都很好。但我发现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();
    }
}

2 个答案:

答案 0 :(得分:0)

android:largeHeap="true"

你的代码应该是这个......

答案 1 :(得分:0)

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

删除这些代码后,它运行良好。 但是,很奇怪只有特定位置的项目会重新绑定。