Duplication in Checkbox selection in RecyclerView

后端 未结 4 1886
无人共我
无人共我 2020-12-11 23:38

Below is the my code.

holder.followDiseaseCheckBox.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
          


        
4条回答
  •  时光说笑
    2020-12-12 00:18

    The recycler view recycles the view in OnBindViewHolder. So when items are clicked it gets reflected in some other positions. To create a global SparseBooleanArray to store the clicked position.

    private final SparseBooleanArray array=new SparseBooleanArray();
    

    Then inside final viewholder add the clickListener and onClick store the position of the clicked item.

    public class ViewHolder extends RecyclerView.ViewHolder {
        public YOURVIEW view;
        public ViewHolder(View v) {
            super(v);
            view = (YOURVIEW) v.findViewById(R.id.YOURVIEWID);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    array.put(getAdapterPosition(),true);
                    notifyDataSetChanged();
                }
            });
        }
    }
    

    And in inside OnBindViewHolder,

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        if(array.get(position)){
            holder.followDiseaseCheckBox.setChecked(true);
        }else{
            holder.followDiseaseCheckBox.setChecked(false);
        }
    }
    

提交回复
热议问题