Chinmay
Chinmay

Reputation: 119

Cardview - Set different background color for each element

I'm working on improving my RecyclerView and CardView skills as I'm new to this.

I created a CardView layout and RecyclerView layout and then Layout Manager and View adapter, minimum that's required to get the app looking like this -

https://i.sstatic.net/DZzNi.jpg

What I want to do is - I want different background colors for every element. For example - Red for "Froyo" , Amber "Gingerbread" and so on.

Any way I can do it?

Also, I want elements separated by 1dp

Thank you

Upvotes: 6

Views: 8080

Answers (2)

BHAVYA SINGH
BHAVYA SINGH

Reputation: 21

For separating element my 1 density pixel: Modify your widget.Card View and specify the required space in your relative layout.[Change your widget.card view accordingly] https://i.sstatic.net/nSJ7W.png

Upvotes: 2

rusted brain
rusted brain

Reputation: 1062

Yes you can do that in RecyclerViews onBindViewHolder method by referring to each card by it's position.

 public void onBindViewHolder(MyViewHolder holder, int position) {
    if(position==1)
       holder.view.setBackgroundColor(Color.RED);
    else if(position==2)
       holder.view.setBackgroundColor(Color.parseColor("#amberColorCode")); //and so on..
}

here view is your TextView or any other view which you are using as RecyclerView row item.

Upvotes: 14

Related Questions