【发布时间】:2019-04-27 21:22:33
【问题描述】:
我有以下功能:
override fun insertUpdatedItems(items: List<AutomobileEntity>) {
if (!items.isEmpty()) {
items.forEachIndexed { index, automobileEntity ->
if (automobileEntity.id == items[index].id) {
automobileCollection[index] = items[index]
notifyItemInserted(index)
}
}
}
}
我用于为 recyclerview 提供数据,我正在尝试插入已在 automobileCollection 中的更新/编辑项目,其大小始终返回 10 项目,但 items 列表可能会有所不同1 到 10。
它应该按id 比较项目,但我目前使用此功能得到的是已编辑的项目只是插入到 recyclerview 的适配器中,而不是被视为已经存在的项目。
相反,如果我使用 automobileCollection 进行迭代,我会得到 IndexOutOfBoundsException,因为大多数时候 items 列表小于 automobileCollection。
【问题讨论】:
-
你可以跳过外部条件。如果
items为空,则forEachIndexed什么也不做...您用index迭代items,然后将其与自身进行比较(automobileEntry是items的一个元素)。有了这个找到的项目(基本上是每个),您使用该索引(项目列表!!!)来更新不相关的automobileCollection...您实际上想要实现什么?并且请确保您理解我之前写的内容......这对于处理forEach等是必不可少的。
标签: android list collections kotlin