Reputation: 21
I'm trying to highlight onmy one item on my recyclerview when user click. But I have an unexpected behavior.
When I click on one item, the adapter logs me that that one is selected and hightlighted. But when I scroll, I see that there are other items highlighted.
Any help on that issue will be really appreciate.
My codes:
My Adapter
public class ChooseRecipientAdapter extends RecyclerView.Adapter<ChooseRecipientViewHolder> {
@Override
public ChooseRecipientViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_recipients_item, null);
ChooseRecipientViewHolder cv = new ChooseRecipientViewHolder(this.context, v);
return cv;
}
@Override
public void onBindViewHolder(final ChooseRecipientViewHolder holder, final int position) {
RecipientItem settingsRecipients = recipientItems.get(position);
settingsRecipients.holder = holder;
holder.title.setText(settingsRecipients.title);
holder.recipient = recipients.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedItem < 0) {
selectedItem = position;
holder.isSelected = true;
holder.itemView.setSelected(true);
holder.title.setTextColor(context.getResources().getColor(R.color.color_background));
} else if (holder.isSelected) {
selectedItem = -1;
holder.isSelected = false;
holder.itemView.setSelected(false);
holder.title.setTextColor(context.getResources().getColor(R.color.textColorPrimary));
ChooseRecipientActivity.recipient = null;
} else {
if (getItem(selectedItem).holder != null) {
getItem(selectedItem).holder.isSelected = false;
getItem(selectedItem).holder.itemView.setSelected(false);
getItem(selectedItem).holder.title.setTextColor(context.getResources().getColor(R.color.textColorPrimary));
selectedItem = position;
holder.isSelected = true;
holder.itemView.setSelected(true);
holder.title.setTextColor(context.getResources().getColor(R.color.color_background));
ChooseRecipientActivity.recipient = holder.recipient;
}
}
}
});
}
My ViewHolder
public class ChooseRecipientViewHolder extends RecyclerView.ViewHolder {
public String id;
public Context context;
public ImageView leftImageView;
public TextView title;
public boolean isSelected = false;
public Recipient recipient;
public View itemView;
public ChooseRecipientViewHolder(final Context context, View view) {
super(view);
this.context = context;
this.leftImageView = (ImageView) view.findViewById(R.id.leftIcon);
this.title = (TextView) view.findViewById(R.id.title);
itemView = view;
}
}
A screenshot:
Upvotes: 0
Views: 6363
Reputation: 16038
The issue is that you need to reset your ViewHolder
selected status if the row isn't selected.
if(selected) {
setRowColour();
} else {
resetColourToDefaults();
}
This is extremely important, because RecyclerView
will reuse ViewHolder
rows as you scroll up and down. A reused row will retain the formatting that was applied to it previously.
Upvotes: 1