mardi 30 avril 2019

Get list of checked checkboxes from recyclerview

I have a Recyclerview that contains a number of checkboxes. these checkboxes received from API(Checkboxes text and id). I want to get a list of ids of checked checkboxes to send to the server. One of my solutions is :

  1. create a data model(Info_Checkbox) that contain method get and set ID.
  2. create ArrayList.
  3. set checked checkboxes id to this array list and use this array to send params to server.

But my code is incorrect! when I checked a number of checkboxes, array list save the last checkboxes id. can you say another solution or fix this error?

Context context;
public ArrayList<Info_Filter> items = new ArrayList<>();
public SparseBooleanArray array = new SparseBooleanArray();
public ArrayList<Info_Checkbox> checkboxes = new ArrayList<>();
private Info_Checkbox info_checkbox = new Info_Checkbox();
public AdapterRecyFilterGroup(Context context, ArrayList<Info_Filter> items) {
    this.context = context;
    this.items = items;
}
@NonNull
@Override
public SetViewHolderFilter onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.sample_filter_grouping, viewGroup, false);
    return new SetViewHolderFilter(view);
}
@Override
public void onBindViewHolder(@NonNull SetViewHolderFilter setViewHolderFilter, int i) {
    setViewHolderFilter.checkBox.setText(items.get(i).getName());
    if (array.get(i)) {
        setViewHolderFilter.checkBox.setChecked(true);
    } else {
        setViewHolderFilter.checkBox.setChecked(false);
    }
}
@Override
public int getItemCount() {
    return items == null ? 0 : items.size();
}

public class SetViewHolderFilter extends RecyclerView.ViewHolder {
    CheckBox checkBox;
    public SetViewHolderFilter(@NonNull final View itemView) {
        super(itemView);
        checkBox = itemView.findViewById(R.id.cb_filter);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (array.get(getAdapterPosition())) {      //!checked
                    array.put(getAdapterPosition(), false);
                    info_checkbox.setId(items.get(getAdapterPosition()).getId());
                    checkboxes.remove(info_checkbox);
                } else {        //checked
                    array.put(getAdapterPosition(), true);
                    info_checkbox.setId(items.get(getAdapterPosition()).getId());
                    checkboxes.add(info_checkbox);
                }
                notifyDataSetChanged();
            }
        });
    }
}




Aucun commentaire:

Enregistrer un commentaire