Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of a single item in RecyclerView?

I have a problem with setting color from resources for an item in RecyclerView. I've tried this two methods but none works. Any ideas what am I doing wrong?

holder.alert.setTextColor(R.color.alertGreen);
holder.alert.setTextColor(getResources().getColor(R.color.alertGreen));
like image 790
Dominik Avatar asked Dec 04 '22 22:12

Dominik


2 Answers

Use ContextCompat to get color.

holder.alert.setTextColor(ContextCompat.getColor(context, R.color.alertGreen));
like image 138
Rahul Avatar answered Dec 06 '22 12:12

Rahul


To update the color for the Single item you can follow below technique,

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

// Green color to set to specific item in the view [By referencing the position you need to handle the view]
int color1 = ContextCompat.getColor(context, R.color.alertGreen));

// Red color to set to remaining Views
int color2 = ContextCompat.getColor(context, R.color.alertRed));

     if (position == 1) {
       holder.alert.setTextColor(color1);
     } else {
       holder.alert.setTextColor(color2);
     }
}
like image 25
Takermania Avatar answered Dec 06 '22 12:12

Takermania