简体   繁体   中英

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();
}

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM