Search code examples
javaandroidandroid-recyclerviewbackground-color

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));
    }
}

Solution

  • Try using setBackgroundColor method on the root view of your RecyclerView single item, and not on the itemView. something like this:

    holder.yourRootView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorLightGrey));
    

    Don't forget to find it first, in your ViewHolder constructor:

    public class CityViewHolder extends RecyclerView.ViewHolder {
    
        private FrameLayout yourRootView;
    
        public ViewHolder(View v) {
            super(v);
    
            yourRootView = (FrameLayout) v.findViewById(R.id.item_root_view);
        }
    }
    

    You can use any view type instead of FrameLayout according to your item.