I am new in android , recently I have learned recyclerview
and i want to change the color of rows.
Example: I have 10 rows and I want to change color like 5 rows blue and 5 rows red.Alternate rows color should be like this.
From where I have to change this by Adapter or by MainActivity. Please help me
By default it have 5. you can increase as per your need. Save this answer.
addItemDecoration(headerDecoration); The decoration is also reusable since there is no need to modify the adapter or the RecyclerView at all.
This viewType variable is internal to the Adapter class. It's used in the onCreateViewHolder() and onBindViewHolder to inflate and populate the mapped layouts. Before we jump into the implementation of the Adapter class, let's look at the types of layouts that are defined for each view type.
setHasFixedSize(true) means the RecyclerView has children (items) that has fixed width and height.
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"));
}
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);
}}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With