繁体   English   中英

如何在 Android 中为 List 使用 forech 条件

[英]How to use forech condition for List in Android

在我的应用程序中,我有一个List ,在这个List我有一个integer数值。
我想用List这个integer检查帖子id ,如果这个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 = ""
)

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

我该如何解决?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM