我在設置RecyclerView
中某個項目的資源時遇到問題。 我試過這兩種方法,但都無效。任何想法我做錯了什麼?如何更改RecyclerView中單個項目的顏色?
holder.alert.setTextColor(R.color.alertGreen);
holder.alert.setTextColor(getResources().getColor(R.color.alertGreen));
我在設置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));
好的,這個工作。謝謝 ;) – Dominik
在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);
}
}
在這裏發佈您的項目xmll和適配器類 –
'setTextColor(Color.parseColor( 「#54D66A」)); ' –