vendredi 29 septembre 2017

How to select single checkbox in a recycler view with multiple checkboxes

There are answers of this questions but none of them solved my problem .Below is my code .

public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.MyViewHolder> {
Context context;
private List<Quiz_G_S> quiz_g_sList = null;
int selectedPosition = -1;


public QuizAdapter(Context context, List<Quiz_G_S> list) {
    this.context = context;
    this.quiz_g_sList = list;
}


@Override
public QuizAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.quiz_single_row, parent, false);

    return new MyViewHolder(itemView);

}

@Override
public void onBindViewHolder(final QuizAdapter.MyViewHolder holder, int position) {

    final int pos = position;

    holder.answers.setText(quiz_g_sList.get(pos).getMCQ());


    if (selectedPosition == pos) {
        holder.checkBox.setChecked(true);

    } else {
        holder.checkBox.setChecked(false);

    }


    holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            selectedPosition = holder.getAdapterPosition();
            QuizAdapter.this.notifyDataSetChanged();

        }
    });


}


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

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView answers;
    CheckBox checkBox;

    public MyViewHolder(View v) {
        super(v);

        answers = (TextView) v.findViewById(R.id.quiz_adap_ans);
        checkBox = (CheckBox) v.findViewById(R.id.quiz_adap_check);

    }
}

}
Above is my adapter code. There is an error on notifyDataSetChanged. I guess the logic is right but i don't know how to refresh checkbox state.The only thing I know is notifyDataSetChanged is there any other method to refresh or is there any workaround for this problem




Aucun commentaire:

Enregistrer un commentaire