Reputation: 51
hello i want to change the color of specific items in recycler view. i have done this using this code.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
LayoutInflater inflater;
Context context;
clickME click;
View view;
ArrayList<String > data;
public CustomAdapter(Context context,ArrayList<String> data) {
this.context=context;
this.data=data;
inflater= LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view=inflater.inflate(R.layout.list_row,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int select=4;
if(select == position) {
view.setBackgroundColor(Color.BLUE);
Toast.makeText(context,""+position,Toast.LENGTH_SHORT).show();
} else {
view.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context,""+position,Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}
i have successfully change the background color of item in position 4, but when i scroll down the background color of item at position 14 also change. i don't know why this happening kindly solve my issue
Upvotes: 2
Views: 6810
Reputation: 20346
You shouldn't reuse view from onCreateViewHolder()
. Code will be something like this:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int select = 4;
if (select == position) {
holder.itemView.setBackgroundColor(Color.BLUE);
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}
Upvotes: 2
Reputation: 770
The problem is you're not recycling your view
View. You have not posted your ViewHolder code, but you should use holder.view.setBackgroundColor(...)
instead of view.setBackgroundColor(...)
in your onBindViewHolder
method.
Upvotes: 4