Inconsistency detected in RecyclerView, How to change contents of RecyclerView while scrolling

前端 未结 26 2485
借酒劲吻你
借酒劲吻你 2020-12-01 00:59

I\'m using RecyclerView to display name of the items. My row contains single TextView. Item names are stored in List mItemList<

26条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 01:57

    Although a couple of useful hyperlinks about this issue are given in the accepted answer, it is not true that this behavior of RecyclerView while scrolling is a bug.

    If you see this exception, most probably you forget to notify the adapter after the content of RecyclerView is "changed". People call notifyDataSetChanged() only after an item is added to the data set. However, the inconsistency occurs not only after you refill the adapter, but also when you remove an item or you clear the data set, you should refresh the view by notifying the adapter about this change:

    public void refillAdapter(Item item) {
    
        adapter.add(item);
        notifyDataSetChanged();
    
    }
    
    public void cleanUpAdapter() {
    
        adapter.clear();
        notifyDataSetChanged(); /* Important */
    
    }
    

    In my case, I tried to clean up the adapter in onStop(), and refill it in onStart(). I forgot to call notifyDataSetChanged() after the adapter is cleaned by using clear(). Then, whenever I changed the state from onStop() to onStart() and swiftly scrolled the RecyclerView while the data set is reloading, I saw this exception. If I waited the end of reloading without scrolling, there would be no exception since the adapter can be reinstated smoothly this time.

    In short, the RecyclerView is not consistent when it is on view change. If you try to scroll the view while the changes in the data set are processed, you see java.lang.IndexOutOfBoundsException: Inconsistency detected. To eliminate this problem, you should notify the adapter immediately after the data set is changed.

提交回复
热议问题