Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -

http://i.stack.imgur.com/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

like image 823
Chinmay Avatar asked Nov 25 '15 09:11

Chinmay


People also ask

How do I customize my CardView?

Customized CardView First, add a CardView dependency to the application-level build. gradle file. Then create a drawable background for the cards. For that, create a new drawable resource file inside the drawable folder.

What is difference between CardView and RecyclerView?

With the help of CardView, we can add radius and elevation to our items of RecyclerView. CardView gives a rich look and feels to our list of data. RecyclerView: RecyclerView is an extended version of ListView. in RecyclerView we can load a large amount of data and items of RecyclerView can have a custom design.


2 Answers

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.

like image 109
rusted brain Avatar answered Sep 20 '22 07:09

rusted brain


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.stack.imgur.com/nSJ7W.png

like image 26
BHAVYA SINGH Avatar answered Sep 23 '22 07:09

BHAVYA SINGH