我想在recyclerview项目或项目的背景中更改文本的文本颜色,但我无法更改。它只改变了一些项目。我为这些代码尝试了几十次。它会更改相同项目的颜色,但不会更改if语句的所有项目。我也试过runOnUiThrad,但仍然无法改变。
getQuantity()和getLowQuantityAlertValue()方法返回double。
if语句有问题吗?
@Override
public void onBindViewHolder(@NonNull ProductViewHolder productViewHolder, int position) {
NumberFormat format = NumberFormat.getCurrencyInstance();
Product mCurrent = objects.get(position);
String pieces = mCurrent.getQuantity() + " " + mCurrent.getAmountType() + " " + productViewHolder.context.getText(R.string.pieces);
if (mCurrent.getQuantity() < 1.0) {
pieces = productViewHolder.context.getText(R.string.out_of_stock).toString();
productViewHolder.itemQuantity.setTextColor(Color.RED);
}
if (mCurrent.getQuantity() <= mCurrent.getLowQuantityAlertValue()) {
pieces = mCurrent.getQuantity() + " " + mCurrent.getAmountType() + " " + productViewHolder.context.getText(R.string.pieces);
productViewHolder.itemQuantity.setTextColor(context.getResources().getColor(R.color.orange));
}
productViewHolder.itemName.setText(mCurrent.getName());
productViewHolder.sellingPrice.setText(String.valueOf(format.format(mCurrent.getPerSellingPrice())));
productViewHolder.itemQuantity.setText(pieces);
productViewHolder.listItemBarcode.setText(mCurrent.getBarcode());
if (mCurrent.getImageUrl() != null && !mCurrent.getImageUrl().equals("")) {
Glide.with(productViewHolder.listItemImage.getContext())
.load(mCurrent.getImageUrl())
.apply(new RequestOptions().placeholder(R.drawable.noimage)
.error(R.drawable.noimage))
.into(productViewHolder.listItemImage);
} else {
productViewHolder.listItemImage.setImageResource(R.drawable.noimage);
}
}
请记住始终在onBindViewHolder方法中处理'else'情况。您的ViewHolders正在重复使用列表元素,因此颜色可以随机更改(如果您没有将其设置回默认值)。所以你必须在'else'的情况下设置一些默认颜色。您的条件将如下所示:
if (mCurrent.getQuantity() < 1.0) {
pieces = productViewHolder.context.getText(R.string.out_of_stock).toString();
productViewHolder.itemQuantity.setTextColor(Color.RED);
} else if (mCurrent.getQuantity() <= mCurrent.getLowQuantityAlertValue()) {
pieces = mCurrent.getQuantity() + " " + mCurrent.getAmountType() + " " + productViewHolder.context.getText(R.string.pieces);
productViewHolder.itemQuantity.setTextColor(context.getResources().getColor(R.color.orange));
} else {
productViewHolder.itemQuantity.setTextColor(Color.RED) // any default color
}