繁体   English   中英

NotifyDataSetChanged无法正确更新RecyclerView

[英]NotifyDataSetChanged does not update the RecyclerView correctly

我正在尝试在我的recyclerview适配器中实现一个相当基本的逻辑,但是notifyDataSetChanged()给我带来了很大的麻烦。

我有一个看起来像这样的过滤器方法:

fun filter(category: Int) {
    Thread(Runnable {
        activeFiltered!!.clear()

        if (category == -1) {
            filterAll()
        } else {
            filterCategory(category)
        }

        (mContext as Activity).runOnUiThread {
            notifyDataSetChanged()
        }
    }).start()
}

filterAll()filterCategory()函数非常简单:

private fun filterAll() {
    activeFiltered?.addAll(tempList!!)
}

private fun filterCategory(category: Int) {
    for (sub in tempList!!) {
        if (sub.category == category) {
            activeFiltered?.add(sub)
        }
    }
}

当我运行此代码并按类别过滤列表时,activeFiltered列表会正确更新并包含我期望的项目,但是当notifyDataSetChanged()运行时,它只会切出列表的范围而不更新项目。

有没有办法解决这个问题?

我也尝试过,而不是使用notifyDataSetChanged():

activeFiltered!!.forEachIndexed {index, _ ->  notifyItemChanged(index)}

但是问题仍然存在。

这也不是线程问题,因为我尝试将整个逻辑放入主线程,并且列表仍未正确更新。

这是我的onBindViewHolder()

override fun onBindViewHolder(viewHolder: ActiveViewHolder, pos: Int) {
    sub = activeFiltered!![pos]
    inflateView()

}

这是我在onBindViewHolder()文本的地方,sub是在onBindViewHolder()设置的实例变量:

private fun inflateView() {
        viewHolder.title.text = sub.title
    }

似乎onBindViewHolder()的实现不正确。 为了更新列表项,应该使用传入的viewHolder参数(而不是您在onCreateViewHolder()创建的viewHolder )。

正确的实现应该像

override fun onBindViewHolder(viewHolder: ActiveViewHolder, pos: Int) {
    val sub = activeFiltered!![pos]
    inflateView(viewHolder, sub)
}

private fun inflateView(viewHolder: ActiveViewHolder, sub: <YourDataType>) {
    viewHolder.title.text = sub.title
}

顺便说一句,将某些内容保留为成员字段以几种方法访问它不是一个好习惯。 随时将其作为此类方法的参数传递。 在上面的代码中,我将sub作为参数传递,而不是将其存储为成员。

而且也不必保留在onCreateViewHolder()创建的viewHolder 我们通常在某些回调方法(例如onBindViewHolder()等)中需要它们,并且这些方法将接收正确的viewHolder作为参数。

我认为您是在onBindView()中使用原始数组,而不是经过过滤的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM