在RecyclerView的OnBindViewHolder中更改视图的文本颜色或背景颜色

时间:2019-02-21 22:41:45

标签: java android android-recyclerview

我想更改recyclerview项目或项目背景中的文本的文本颜色,但不能更改。它仅更改某些项目。我为这些代码尝试了数十次。它会更改相同项目的颜色,但不会更改if语句为true的所有项目的颜色。我也尝试使用runOnUiThrad,但仍然无法更改。

getQuantity()和getLowQuantityAlertValue()方法返回双精度值。

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);
    }
}

1 个答案:

答案 0 :(得分:2)

请记住,始终要在onBindViewHolder方法中处理“其他”情况。您的ViewHolders被重新用于list元素,因此颜色可以随机更改(如果您未将其设置为默认值)。因此,您必须在“其他”情况下设置一些默认颜色。您的情况将如下所示:

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
        }
相关问题