【问题标题】:add a list of items to a recycler view将项目列表添加到回收站视图
【发布时间】:2019-10-31 04:26:15
【问题描述】:

我想将元素添加到 Android 中的回收站视图显示的项目列表中。

到目前为止,在我的代码中,当列表接近尾声时,我会获取更多项目并将新项目列表附加到当前显示的列表中。然后我调用 notifyDataSetChanged() 但我收到以下错误:

 java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.widget.RecyclerView...

如何在让回收站停留在当前显示的项目上时更新要显示的列表?

这是我的代码:

 private class StatusRecyclerAdapter extends RecyclerView.Adapter<StatusRecyclerHolder> {
    private List<Status> statues;
    private int size;


    private final int LOAD_POSITION = 3;


    public StatusRecyclerAdapter() {
         statues = feed.getStatuses();
    }

    @NonNull
    @Override
    public StatusRecyclerHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        return new StatusRecyclerHolder(layoutInflater, viewGroup);
    }

    @Override
    public void onBindViewHolder(@NonNull StatusRecyclerHolder statusRecyclerHolder, int i) {
        statusRecyclerHolder.bind(statues.get(i));
        if(size - i == LOAD_POSITION){
            getContentNextPage();
        }
    }

    @Override
    public int getItemCount() {
        size = 0;
        if(statues == null){
            Log.i(TAG, "List of status null" );
        }
        else{
            size = statues.size();
        }

        return size;
    }

    private void getContentNextPage(){
        this.statues = Feed.getNextPage();
        }

        notifyDataSetChanged();
    }
}

谢谢!

【问题讨论】:

  • 你能给你看代码吗?
  • 您提供的代码似乎有问题,在 this.statues = Feed.getNextPage(); 之后有关闭括号,它应该在那里吗?

标签: android android-recyclerview view


【解决方案1】:

在我看来,您的代码试图做的是更新 recyclerview WHILE 它正在更新,这可能会以某种方式最终进入无限循环。您可以在其他地方而不是在onBindViewHolder(...) 中调用getContentNextPage(),也许可以从您视图中的StatusRecyclerAdapter 类之外调用它

【讨论】:

    【解决方案2】:

    RecyclerView 不允许你调用 notifyDataSetChanged();在 onBindViewHolder 中。这就是您遇到异常的原因。通过删除 notifyDataSetChanged 尝试它会起作用。

     private void getContentNextPage(){
            this.statues = Feed.getNextPage();
            }
    
            notifyDataSetChanged();//REMOVE THIS LINE
        }
    

    【讨论】: