Search code examples
androidandroid-recyclerviewrealmrecyclerviewadapter

How to set different color for each items in RecyclerViews' GridLayoutManager


I've implemented the GridLayoutManager and it is working fine. I've used a CardView for the item layout.

Screenshot of the GridLayoutManager:

image

I just want to set a different color for the first five items in the list and repeat the same colors for the next five. For example, If my list contains 10 items, then the first five items have different colors suppose red, green, blue, yellow, pink and then from the item 6 - 10 these same colors should be set as the background color. I've tried to set the CardView background color using setCardBackgroundColor(Color.parseColor("#FF6363")).But this simply changes the background color of all the items. Is there any way to set different colors to items?

@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.device_card, parent, false);
    CardView dc = view.findViewById(R.id.cardViewCard);
    dc.setCardBackgroundColor(Color.parseColor("#FF6363"));

    return new ViewHolder(view);
}

Solution

  • You got to change it in your onBindViewHolder.

    I think this code may work for you, just use the switch with the modulus of your position plus 1 divided by 5, and then In every case, you set the color you want as background.

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    
        switch((position+1)%5) {
            case 0: 
                dc.setCardBackgroundColor(Color.parseColor("#Color5"));
                break;
            case 1:
                dc.setCardBackgroundColor(Color.parseColor("#Color1"));
                break;
            case 2:
                dc.setCardBackgroundColor(Color.parseColor("#Color2"));
                break;
            case 3:
                dc.setCardBackgroundColor(Color.parseColor("#Color3"));
                break;
            case 4:
                dc.setCardBackgroundColor(Color.parseColor("#Color4"));
        }
    }