Item of one color or another (RecyclerView)

2

What I want to achieve is the following, that an element is painted in one color and the next in another:

-----------
item0: azul
-----------
item1: amarillo
-----------
item2: azul
-----------
item3: amarillo
-----------
...

and thus without end, that is to say, to use two different colors and that each item is having the color that does not have the one of above.

At the moment what I have achieved is to assign it myself, but one by one ..

 @Override
    public void onBindViewHolder(RecordatoriosViewHolder holder, int position) {
        final Recordatorios singleRecordatorios = listRecordatorioses.get(position);
        if(position==1)
            holder.cardview_item.setBackgroundColor(Color.BLUE);
        else if(position==2)
            holder.cardview_item.setBackgroundColor(Color.YELLOW);
    
asked by UserNameYo 20.06.2017 в 16:40
source

2 answers

2

This seems to me that you already did it, remember that position is the index of each element (start with 0 do not forget it), you can define each one manually but it is best to determine when a number is even (0 is considered odd or even

private boolean esPar(int n){
    if ( ( n % 2 ) == 0 ) {
        return true; //Par
    } else {
        return false;//Impar
    }
}

Applying to your code would be like this:

@Override
    public void onBindViewHolder(RecordatoriosViewHolder holder, int position) {
        final Recordatorios singleRecordatorios = listRecordatorioses.get(position);
        if((position % 2) == 0)
            holder.cardview_item.setBackgroundColor(Color.BLUE);
        else 
            holder.cardview_item.setBackgroundColor(Color.YELLOW);
...
}
    
answered by 20.06.2017 / 17:01
source
2

You can check if the position of the item is even or odd, so assign it to blue or yellow as appropriate

if(position%2==0){
   holder.cardview_item.setBackgroundColor(Color.BLUE);
} else {
   holder.cardview_item.setBackgroundColor(Color.YELLOW);
}
    
answered by 20.06.2017 в 16:50