簡體   English   中英

如何在RecyclerView中更改單個項目的顏色?

[英]How to change color of a single item in RecyclerView?

我在RecyclerView為項目的資源設置顏色時遇到問題。 我嘗試過這兩種方法但沒有效果。 有什么想法我做錯了什么?

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

使用ContextCompat獲取顏色。

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

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

您應該使用ContextCompact而不是getResources()因為deprecated此方法。

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

要更新單個項目的顏色,您可以按照以下技術,

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

使用ContextCompat的另一種方法是:

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

暫無
暫無

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

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