Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of every second element in RecyclerView

My RecyclerView is having some elements in it. Now I tried to change background color of every second element, but my code doesn't work... It is my method onBindViewHolder

public void onBindViewHolder(CityViewHolder holder, int position) {
    String cityName = cityList.get(position);
    holder.cityTextView.setText(cityName);

    if (position%2 == 0) {
        holder.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorLightGrey));
    }
    else {
        holder.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorGrey));
    }
}
like image 466
y07k2 Avatar asked Mar 13 '23 03:03

y07k2


1 Answers

Do it like this instead (same place in your adapter):

if (position%2 == 0) {
     holder.itemView.setBackgroundColor(Color.parseColor("#fafafa"));
} else {
     holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));
}
like image 138
ekashking Avatar answered Mar 16 '23 03:03

ekashking