刷新时滚动时 RecyclerView 崩溃

RecyclerView Crashing when scrolling while refreshing

我正在回收站视图中显示我从 WordpressAPI 获得的一些文章。为了触发重新加载,我使用了 SwipeRefreshLayout。当用户在应用程序加载新文章时重新加载并向下滚动时,应用程序崩溃并且出现以下错误

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionThomsLineArticleViewHolder{5c87efc position=2 id=-1, oldPos=-1, pLpos:-1 no parent}

我将文章以 10 个为一包的形式(也称为 Wordpress 的页面)存储在视图模型中,这是我用来更新给定页面的代码:

fun setArticlePage(id: Int, content:ThomsLineWordpressArticlePage, recyclerAdapter: ThomsLineRecyclerAdapter){

        //Only do Something if actually something changed
        if (_articles.value == null || id >= _articles.value!!.size || (id < _articles.value!!.size && !_articles.value!!.get(id).equals(content))) {
            //If there were no articles previously
            if (_articles.value == null) _articles.value = arrayListOf(content)

            //if the Page is completly new
            else if (id >= _articles.value!!.size) _articles.value?.add(content)

            //If it's just a old Page updating
            else if (id < _articles.value!!.size) _articles.value?.set(id, content)

            // Save the new Values
            _articles.postValue(_articles.value)
            
            //Update Recycler View
            recyclerAdapter.notifyItemChanged(id)
        }
    }

编辑:我应该说当用户不滚动时没有错误,当用户在重新加载时滚动时应用程序崩溃

当您尝试刷新 (recyclerAdapter.notifyItemChanged(id)) 回收器视图时,在其最后更新操作尚未完成时发生不一致。

几乎没有什么问题不清楚。 您是否在循环内调用 setArticlePage 方法?然后你应该在循环完成后刷新回收器视图。

除此之外,尝试一次加载 New Articals 一页。在最后一次调用 API 完成之前不允许加载新的文章页面。

对不起,错误实际上不是 RecyclerView 本身,而是我代码的其他部分:我总是将页面加载到给定点,然后删除所有页面,这在加载新页面时,RecyclerView 想要访问的值实际未加载。

抱歉耽误了您的时间