1

I have the following code on my RecyclerView:

class TaskViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener
    {
        var mId: TextView = v.task_id
        var mDescription: TextView = v.task_description
        var mCard: CardView = v.task_card
        var mView: View = v
    }

override fun onBindViewHolder(holder: TaskViewHolder, position: Int)
{
    // Initialize ViewHolder content
    holder.mId.text = items[position].getID().toString()
    holder.mDescription.text = items[position].getDescription()
    holder.mTask = items[position]

    for (elem in priorities)
    {
        if (elem.getID() == items[position].getPriority())
        {
            holder.mCard.setCardBackgroundColor(Color.parseColor("#c2c2c2"))
            break
        }
    }
}

I don't know why, but CardView backgroundColor isn't changing.

If I use the following code, it works correctly:

holder.mCard.setCardBackgroundColor(ContextCompat.getColor(holder.mView.context, R.color.priority3))

What I should do to set CardBackgroundColor progrmatically?

Lechucico
  • 1,914
  • 7
  • 27
  • 60

2 Answers2

1

First of all, You need to provide else part as transparent or another color to avoid color duplicate render issue. second, you have to pass context from your activity or fragment to adapter and that context will be used to get color like below.

if (elem.getID() == items[position].getPriority())
    {
        holder.mCard.setCardBackgroundColor(ContextCompat.getColor(mContext, [first color]))  
    } else {
        holder.mCard.setCardBackgroundColor(ContextCompat.getColor(mContext,[second color]))
    }
Dipakk Sharma
  • 976
  • 1
  • 8
  • 11
0

Try replacing "#c2c2c2" with "#ffc2c2c2" to make sure you provide a correct alpha for the background colour. On android, this extra byte added at the beginning represents the alpha of the colour:

#ffc2c2c2

  • ff: alpha
  • c2: red
  • c2: green
  • c2: blue