Dominik
Dominik

Reputation: 73

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

Upvotes: 5

Views: 5331

Answers (5)

Dannex Daniels
Dannex Daniels

Reputation: 31

An alternative of using ContextCompat is this:

holder.alert.setTextColor(context.getResources().getColor(R.color.alertGreen));

Upvotes: 0

Takermania
Takermania

Reputation: 1385

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

Upvotes: 3

Harsh Mittal
Harsh Mittal

Reputation: 459

You should use ContextCompact instead of getResources() because this method is deprecated.

holder.alert.setTextColor(ContextCompat.getColor(context, R.color.red));

Upvotes: 2

Zoltan Szilagyi
Zoltan Szilagyi

Reputation: 292

In onBindViewHolder(RecyclerView.ViewHolder holder, int position) method you can change the current element color:

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    holder.alert.setTextColor(R.color.alertGreen);
    holder.alert.setTextColor(getResources().getColor(R.color.alertGreen);
}

And use ContextCompat to get the color:

ContextCompat.getColor(context, R.color.alertGreen));

Upvotes: 1

Rahul
Rahul

Reputation: 10635

Use ContextCompat to get color.

holder.alert.setTextColor(ContextCompat.getColor(context, R.color.alertGreen));

Upvotes: 11

Related Questions