簡體   English   中英

在RecyclerView的OnBindViewHolder中更改視圖的文本顏色或背景顏色

[英]Changing text color or background color of view in OnBindViewHolder of 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);
    }
}

請記住,始終要在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
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM