In Android RecyclerView How to change the color of Alternate rows
In the onBindViewHolder of your adapter simply get the poisition and check that whether it is even or odd. If it is even, set the background color of your layout to red else blue
@Override
public void onBindViewHolder(final ViewHolder viewHolder, int position) {
if(position%2 == 0){
viewHolder.containerLayout.setBackgroundColor(R.color.RED);
} else {
viewHolder.containerLayout.setBackgroundColor(R.color.BLUE);
}}
With CardView in Kotlin
internal fun bind(d: Detalle, position: Int, listener: OnItemClickListener) {
if (position % 2 == 1) {
cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.blue_logo))
} else {
cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.colorWhite))
}
Multiples Colors
when {
p % 4 == 0 -> cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.yellow))
p % 4 == 1 -> cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.green))
p % 4 == 2 -> cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.blue))
p % 4 == 3 -> cardViewPrincipal.setCardBackgroundColor(ContextCompat.getColor(itemView.context, R.color.red))
}
You can change the color of alternate row by adding the following code on your Adapter class. You can also change the images of your row by using this code.
Put this code inside OnBindViewHolder
in Adapter Class.
if(position %2 == 1)
{
holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
// holder.imageView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#FFFAF8FD"));
// holder.imageView.setBackgroundColor(Color.parseColor("#FFFAF8FD"));
}
I believe one problem with all of these solutions is that onBindViewHolder
doesn't get called in certain cases. If you use notify methods like notifyItemInserted(int position)
, you could potentially have rows stacked on top of each other with the same color - no good. You will need to call notifyItemChanged
on every other item to re-render the background color corresponding to the new position.
Using the re-render all method notifyDataSetChanged()
will fix this (but is less efficient than only updating specific rows), and if you don't dynamically change the contents of a RecyclerAdapter
while the user is on the screen, you won't have this issue.