首页 > 解决方案 > 如何检查recyclerView中是否存在新添加的项目?

问题描述

实际上我正在开发一个库存应用程序,我在其中扫描一些 EAN 代码,然后我插入一个项目的数量,然后我将它添加到 recyclerView 中的 ArrayList。

现在我没有问题,因为我已经制作了库存部分,其中项目必须在 recyclerView 中为每个项目有不同的行,但现在我必须制作订单部分,如果 ArrayList 中还存在一个项目,我必须总结它的数量并将其放在recyclerView 的顶部。

当我要添加一个新项目并检查它是否存在于 ArrayList 中时,我试图制作类似 for 循环的东西,如果它存在,我打算将该项目数量与旧项目相加,但问题是有时应用程序会崩溃,并且该项目不会在 recyclerView 之上。

你对我该怎么做有什么建议吗?

for (ItemModel item : itemModel) {
    if (item.getCodiceArticolo()
            .equals(code.getText()
                        .toString())) {
        item.setQta(String.valueOf(
                Integer.parseInt(item.getQta()) + 1));
    }
}

我试图做类似的东西。

标签: androidandroid-recyclerview

解决方案


试试这个代码:

ItemModel matchedItem = null;
int matchedItemIndex = -1;
for (ItemModel item : itemModel) {
    if (item.getCodiceArticolo()
            .equals(code.getText()
                        .toString())) {
        item.setQta(String.valueOf(
                Integer.parseInt(item.getQta()) + 1));
        matchedItem = item;
        matchedItemIndex = itemModel.indexOf(item);
        break;
    }
}

if (matchedItemIndex > -1) {
    itemModel.remove(matchedItem);
    itemModel.add(
            0,
            matchedItem);
    notifyItemMoved(index,
                    0);
}

推荐阅读