2017-03-21 200 views
1

我在設置RecyclerView中某個項目的資源時遇到問題。 我試過這兩種方法,但都無效。任何想法我做錯了什麼?如何更改RecyclerView中單個項目的顏色?

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

在這裏發佈您的項目xmll和適配器類 –

+1

'setTextColor(Color.parseColor( 「#54D66A」)); ' –

回答

4

使用ContextCompat可以獲得顏色。

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

好的,這個工作。謝謝 ;) – Dominik

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

您應該使用ContextCompact而不是getResources(),因爲這種方法是deprecated

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

要更新,你可以按照下面的技術單項的顏色,

@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); 
    } 
} 
相關問題