簡體   English   中英

將項目列表添加到回收站視圖

[英]add a list of items to a recycler view

我想將元素添加到 Android 中的回收站視圖顯示的項目列表中。

到目前為止,在我的代碼中,當列表接近尾聲時,我會獲取更多項目,append 是顯示的當前列表的新項目列表。 然后我調用 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();
    }
}

謝謝!

在我看來,您的代碼試圖做的是在更新recyclerview的同時更新它,這可能會以某種方式最終陷入無限循環。 您可以在其他地方調用getContentNextPage()而不是onBindViewHolder(...) ,也許可以從您認為的StatusRecyclerAdapter class 之外調用它

RecyclerView 不允許你調用 notifyDataSetChanged(); 在 onBindViewHolder 中。這就是您遇到異常的原因。 嘗試刪除 notifyDataSetChanged 它將起作用。

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

        notifyDataSetChanged();//REMOVE THIS LINE
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM