Android tutorial

Android recyclerview item color change example

1.5kviews

In this android recyclerview example, we learn to change item color when it clicks. Hey here is the solution to changing the background color of a selected list item in the recycler view list. it’s very easy you can just follow the step for Changing the background color of the selected item in recycler view.

******* Change in onBindViewHolder *******

android recyclerview adapter.

You can follow the below change in your android recyclerview adapter class and set item color on click on an item. When the user clicks recycler view list item background color is changed and pre-selected item color is released same to other.

public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tv.setText(android_versionnames[position]);

holder.linearlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
index=position;
notifyDataSetChanged();
}
});
if(index==position){
holder.linearlayout.setBackgroundColor(Color.parseColor("#FFEB3B"));
holder.tv.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.linearlayout.setBackgroundColor(Color.parseColor("#ffffff"));
holder.tv.setTextColor(Color.parseColor("#6200EA"));
}
}

Android recyclerview adapter

in your adapter row index you can set it as -1 and because of that first time there is not any item is selected.When you select the item potion set on row_index.

here ‘row_index’ is set as ‘-1’ initially

public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tv;
LinearLayout linearlayout;
RecyclerView rv;

public ViewHolder(final View itemView) {
super(itemView);
tv=(TextView)itemView.findViewById(R.id.txtView1);
linearlayout=(LinearLayout)itemView.findViewById(R.id.inrLayout);
rv=(RecyclerView)itemView.findViewById(R.id.recyclerView);
}
}