【问题标题】:Remove duplicate items in list adapter删除列表适配器中的重复项
【发布时间】:2022-01-05 17:58:50
【问题描述】:

我是 Kotlin 编码的新手,无法解决此问题。

我有一个如下所示的 Json 列表:

[
  {
    "id": 01,
    "title": {
      "rendered": "MY TITLE 1"
    },
    "category": [52],

 
  },
 {
    "id": 02,
    "title": {
      "rendered": "MY TITLE 2"
    },
    "category": [52],[64]
  },
{
    "id": 03,
    "title": {
      "rendered": "MY TITLE 3"
    },
    "category": [64]
  }
...
]

我设法编写了一个带有 recyclerview 的列表适配器,以显示每个标题的列表。 现在我想要另一个只有每个类别的recyclerview,但我能实现的只是一个带有重复项的类别列表。我在列表中添加了一个“distinct()”,但无法通过适配器对其进行迭代。

这是我的代码:

在适配器中:

 override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {
        val currentItem = mylist.flatMap { it.category}
        val list2 = currentItem.toList()
        val test = list2[position]
            holder.binding.txtCat.text =test.toString()
    }

模拟器中的结果是: enter image description here

如果我添加一个 .distinct() 来消除这样的重复:

 override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {
        val currentItem = mylist.flatMap { it.category}
        val list2 = currentItem.toList().distinct()
        val test = list2[position]
            holder.binding.txtCat.text =test.toString()
    }

我收到此错误消息: java.lang.IndexOutOfBoundsException:索引:9,大小:9

但如果我将 'val test = list2[position]' 更改为 'val test = list2',结果是:

enter image description here

删除了重复的条目,但我无法在适配器中对其进行迭代???

谢谢你的灯!

【问题讨论】:

  • 您能添加更多您的适配器代码吗?特别是您向适配器提供myList 的部分。
  • 请提供您的适配器的更多代码。
  • mylist 的类型是什么?

标签: android kotlin listadapter


【解决方案1】:

在创建适配器之前尝试删除重复值。既要编辑数据集又要遍历它不是一个好主意。 Here 您可以找到一种方法从您的集合中删除重复值。

为什么会出现 java.lang.IndexOutOfBoundsException? - 因为您使用具有重复值的数据集(例如 [1、2、3、3、3、4、5])创建了适配器,所以适配器知道数据集中存在 7 个元素。然后你通过这行代码val list2 = currentItem.toList().distinct(),你的数据集就变成了[1,2,3,4,5]。不再有 7 个项目,而是 5 个。适配器不知道,仍然会尝试显示 7 个项目。因此,IndexOutOfBoundsException 异常。

【讨论】:

  • 感谢您的回答。我会询问如何做到这一点。可能以某种方式有用。
【解决方案2】:

首先,从mylist.category创建不同的currentList

val currentItem = mylist.flatMap{it.category}.toList().distinct()

然后根据currentItem 列表创建你的适配器

override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {

        holder.binding.txtCat.text = currentItem[position].toString()

}

【讨论】:

  • 我仍然有同样的错误:java.lang.IndexOutOfBoundsException: Index: 9, Size: 9 and override fun getItemCount() = currentItem.size 不起作用。
  • 请分享您的代码
  • 它似乎确实适用于: override fun getItemCount() = stages.flatMap { it.mec_category}.toList().distinct().size ... 不是最可爱的方式,但它有效 ^ ^
  • 你在哪里初始化 currentItem 列表?
  • 不要在 BindViewHolder 上过滤您的数据。在设置适配器之前使用 distinct。那么你不应该得到outofboundexception
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2011-10-04
相关资源
最近更新 更多