我在RecyclerView
中设置资源颜色时遇到了问题。我尝试过以下两种方法,但都不起作用。您有什么想法是我做错了什么吗?
holder.alert.setTextColor(R.color.alertGreen);
holder.alert.setTextColor(getResources().getColor(R.color.alertGreen));
我在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));
如果您想更新单个项目的颜色,可以按照以下步骤进行:
@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);
}
}
ContextCompact
代替getResources()
,因为后者已经被deprecated
。holder.alert.setTextColor(ContextCompat.getColor(context, R.color.red));
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));
使用ContextCompat的另一种替代方法是:
holder.alert.setTextColor(context.getResources().getColor(R.color.alertGreen));
setTextColor(Color.parseColor("#54D66A"));
- IntelliJ Amiya