Anton Kazakov
Anton Kazakov

Reputation: 13

RecyclerView Adapter notifyItemChanged triggers twice

I'm trying to highlight my selected item in recyclerView when it's clicked.But it triggers two items instead. Please help me. Should i store clicked items as arraylist and clear them on new one clicked?

public class StationsAdapter extends RecyclerView.Adapter<StationsHolder> {

List<Station> stations;

public StationsAdapter(List<Station> stations){
    this.stations = stations;
}

public void changeItemAtPosition(int position) {
    notifyItemChanged(position);
}

@Override
public StationsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new StationsHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.stations_item,parent,false));
}

@Override
public void onBindViewHolder(StationsHolder holder, int position) {
    bind(holder);
}

private void bind(final StationsHolder holder) {

    holder.tvTitle.setText(stations.get(holder.getAdapterPosition()).getName());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.tvTitle.setTextColor(ContextCompat.getColor(AppDelegate.getContext(),R.color.colorAccent));
        }
    });
}

@Override
public int getItemCount() {
    return stations.size();
}

}

Upvotes: 0

Views: 1145

Answers (1)

zon7
zon7

Reputation: 539

This is due to recycler reusing the same view when you scroll. In order to fix that, you will have to do the next:

  1. Store the selected item when you click on it. In a variable or in an array if you want more than one item
  2. Check the selected item variable/array in the bind method to know if you have to color it or not

That way it will work flawlessly

Upvotes: 0

Related Questions