java - 如何在 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!
我该如何解决?
解决方案
如果您只想使用forEach
而不是经典的for
-loop MutableList<Basket>
(例如),那么您可以在 Kotlin 中这样做:
data.getBasket().forEach(basket -> {
Log.e("BooksIdLog", bookId + " - " + basket.getBookId());
if (bookId == basket.getBookId()) {
...
} else {
...
}
}
但我认为你的循环工作正常......
我的猜测是您没有正确更新bookId
用于比较的值。检查它在哪里声明、定义和使用...
推荐阅读
- r - R:合并重复条目并按组有条件地选择日期
- c++ - 不能在 Switch Case 中调用函数 - C++
- php - 未定义的方法 Laravel\Lumen\Application::booted()
- angular - 无法在 Leaflet-geotiff 上绘制 geotiff
- mysql - only_full_group_by 不让我显示我想要的表格
- composer-php - 作曲家:如何释放作曲家(演出)使用的大量磁盘空间?
- windows - OpenDDS - 解决方案构建良好,示例运行,但 IDL exe 崩溃
- angular - 角度材料日期选择器在焦点离开时自动选择日期
- sql - 在最后一个'/'之后获取所有内容
- telerik - 打开时单击 Telerik RadWindow 内的按钮