我正在尝试在cardview
中设置不同的背景颜色,但是它不起作用
我有包含颜色的颜色数组
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.MyViewHolder> {
private Context mContext;
private List<String> leavetypeList;
private List<String> leavebalanceList;
public String[] mColors = {
"3F51B5","FF9800","009688","673AB7"
};
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView leavecount,leavename;
public ImageView thumbnail;
public RelativeLayout rlauthor;
CardView cardView;
View viewline;
public MyViewHolder(View view) {
super(view);
leavecount = (TextView)view.findViewById(R.id.tvleavenumber);
leavename = (TextView)view.findViewById(R.id.tvleavetype);
cardView=(CardView) view.findViewById(R.id.cdvdashboard);
}
}
public DashboardAdapter(Context context, List<String> leavetypeList,List<String> leavebalanceList) {
this.mContext = context;
this.leavetypeList = leavetypeList;
this.leavebalanceList = leavebalanceList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.raw_dashboard, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Typeface tf;
tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/HKNova-Medium.ttf");
holder.leavecount.setTypeface(tf);
holder.leavename.setTypeface(tf);
holder.leavecount.setText(leavebalanceList.get(position));
holder.leavename.setText(leavetypeList.get(position));
String color="#"+mColors[position];
for(int c=1;c<mColors.length;c++)
{
holder.cardView.setCardBackgroundColor(Color.parseColor(color));
if(c==mColors.length)
{
c=1;
}
}
}
@Override
public int getItemCount() {
return leavetypeList.size();
}
}
我想要这种类型的输出,但是只获取最后一种颜色,并且如果颜色完成而不是显示其他项目背景颜色,则从color [0]位置开始
任何帮助将不胜感激
答案 0 :(得分:5)
它不会那样工作。您需要将此逻辑放入onBindViewHolder
内,在其中可以借助position
更改颜色。
使用方式
public String[] mColors = {"#3F51B5","#FF9800","#009688","#673AB7"};
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
holder.itemView.setBackgroundColor(Color.parseColor(mColors[position % 4])); // 4 can be replaced by mColors.length
}
看看我如何用前缀#
重新定义mColors数组。因此,您需要在计算颜色时添加#。
答案 1 :(得分:0)
在这种情况下,您匹配一些值,然后像这样设置颜色。 下面的代码添加到适配器类中。
@Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
// below code handle click event on recycler view item.
final String data = mStringList.get(position);
if (data=="RED")
{
// put your logic to set color into card view.
holder.cardView.setBackgroundColor(Color.parseColor(color));
}
holder.textView.setText(data);
holder.firstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClick.getPosition(data); // shared data.
}
});
}