【发布时间】: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',结果是:
删除了重复的条目,但我无法在适配器中对其进行迭代???
谢谢你的灯!
【问题讨论】:
-
您能添加更多您的适配器代码吗?特别是您向适配器提供
myList的部分。 -
请提供您的适配器的更多代码。
-
mylist 的类型是什么?
标签: android kotlin listadapter