首页 > 解决方案 > 如何在 Android 中对 List 使用 forech 条件

问题描述

在我的应用程序中,我有一个List,对此List我有一个integer值。
我想检查一下id这个integer的帖子List,如果这id相等,我应该更改 UI。
我写了下面的代码,但在我的代码中只是更改了最后一项 UI。

我的代码:

for (int i = 0; i <= data.getBasket().size() - 1; i++) {
    Log.e("BooksIdLog", bookId + " - " + data.getBasket().get(i).getBookId());
    if (bookId == data.getBasket().get(i).getBookId()) {
        detailPage_bottomSheetPrintVersion.setBackground(context.getResources()
                .getDrawable(R.drawable.bg_rounded_stroke_red));
        detailPage_bottomSheetPrintVersion.setText(getString(R.string.removeFromBasket));
        detailPage_bottomSheetPrintVersion.setTextColor(context.getResources()
                .getColor(R.color.red));
        detailPage_bottomSheetPrintVersion.setOnClickListener(view -> 
                presenter.callRemoveBookBasketApi(apiHash, userToken, bookId)
            );
    } else {
        detailPage_bottomSheetPrintVersion.setBgColor(context.getResources()
                .getColor(R.color.platinumGray));
        detailPage_bottomSheetPrintVersion.setText(getString(R.string.printVersion));
        detailPage_bottomSheetPrintVersion.setTextColor(context.getResources()
                .getColor(android.R.color.black));
        detailPage_bottomSheetPrintVersion.setOnClickListener(view -> {
            presenter.callAddBookBasketApi(apiHash, userToken, bookId);
        });
    }
}

数据字段:

data class Basket(
    @SerializedName("basket_id")
    val basketId: Int = 0, // 61
    @SerializedName("book_id")
    val bookId: Int = 0, // 156570
    @SerializedName("count")
    val count: Int = 0, // 1
    @SerializedName("id")
    val id: Int = 0, // 156570
    @SerializedName("inventory")
    val inventory: Int = 0, // 0
    @SerializedName("price_of_each_book")
    val priceOfEachBook: String = "", // 0
    @SerializedName("title")
    val title: String = ""
)

例如:
我有 3 个项目List,这 3 个项目的 id 是 = 155060 - 155070 - 154030,当转到详细页面活动时,只需更新这个 id 154030中的 UI,而不是所有的 id!

我该如何解决?

标签: javaandroidlistkotlin

解决方案


如果您只想使用forEach而不是经典的for-loop MutableList<Basket>(例如),那么您可以在 Kotlin 中这样做:

data.getBasket().forEach(basket -> {
    Log.e("BooksIdLog", bookId + " - " + basket.getBookId());
    if (bookId == basket.getBookId()) {
        ...
    } else {
        ...
    }
}

但我认为你的循环工作正常......

我的猜测是您没有正确更新bookId用于比较的值。检查它在哪里声明、定义和使用...


推荐阅读