Mit*_*ana 1 android adapter android-recyclerview
我试图设置不同的背景颜色,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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要这种类型的输出,但只获得最后的颜色,如果颜色完成比显示其他项目背景颜色从颜色[0]位置开始
任何帮助将受到高度赞赏
它不会那样工作.您需要将此逻辑放在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
}
Run Code Online (Sandbox Code Playgroud)
看看我如何重新定义带有#前缀的mColors数组.所以你需要在计算颜色时添加#.