如何在RecyclerView中更改单个项目的颜色?

5

我在RecyclerView中设置资源颜色时遇到了问题。我尝试过以下两种方法,但都不起作用。您有什么想法是我做错了什么吗?

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

请在此处发布您的项目XML,并编写适配器类。 - Quick learner
1
setTextColor(Color.parseColor("#54D66A")); - IntelliJ Amiya
5个回答

11

使用 ContextCompat 获取颜色。

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

3

如果您想更新单个项目的颜色,可以按照以下步骤进行:

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

2
你应该使用ContextCompact代替getResources(),因为后者已经被deprecated
holder.alert.setTextColor(ContextCompat.getColor(context, R.color.red));

1
onBindViewHolder(RecyclerView.ViewHolder holder, int position)方法中,您可以更改当前元素的颜色:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    holder.alert.setTextColor(R.color.alertGreen);
    holder.alert.setTextColor(getResources().getColor(R.color.alertGreen);
}

使用ContextCompat获取颜色:
ContextCompat.getColor(context, R.color.alertGreen));

0

使用ContextCompat的另一种替代方法是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接