简体   繁体   English

RecyclerView Adapter notifyItemChanged触发两次

[英]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. 我试图在单击时在recyclerView中突出显示我选择的项目,但它会触发两个项目。 Please help me. 请帮我。 Should i store clicked items as arraylist and clear them on new one clicked? 我应该将单击的项目存储为arraylist并在单击新的项目时将其清除吗?

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 在bind方法中检查选定的项目变量/数组,以了解是否需要着色

That way it will work flawlessly 这样,它将完美地工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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