Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select just one RadioButton with RecyclerView android?

I have a RecyclerView with RadioButton I just want to select one RadioButton not many in the same time and my code make it works fine, but when I repeat the selection from top to bottom the select disappear how can I fix it please thanks.

enter image description here

private RadioButton lastCheckedRB = null;

 @Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    ContactUsModel contactUsModel = orderList.get(position);
    holder.orderNum.setText(contactUsModel.getOrderNum());
    holder.orderCost.setText(contactUsModel.getOrderCost());

    holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);

            if (lastCheckedRB != null &&lastCheckedRB.isChecked()) {
                lastCheckedRB.setChecked(false);
            }
            //store the clicked radiobutton
            lastCheckedRB = checked_rb;


        }
    });
like image 846
hossam rakha Avatar asked Sep 11 '25 07:09

hossam rakha


1 Answers

You can do as,Use RadioButton I just write without check But this is an hint for you -

 private CompoundButton lastCheckedRB = null;

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    ContactUsModel contactUsModel = orderList.get(position);
    holder.orderNum.setText(contactUsModel.getOrderNum());
    holder.orderCost.setText(contactUsModel.getOrderCost());
    holder.readioBtn.setOnCheckedChangeListener(ls);
    holder.readioBtn.setTag(position);
}

private OnCheckedChangeListener ls = (new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
                                 boolean isChecked) {
        int tag = (int) buttonView.getTag();
        ;
        if (lastCheckedRB == null) {
            lastCheckedRB = buttonView;
        } else if (tag != (int) lastCheckedRB.getTag()) {
            lastCheckedRB.setChecked(false);
            lastCheckedRB = buttonView;
        }

    }
});
like image 167
Sanjay Kumar Avatar answered Sep 14 '25 00:09

Sanjay Kumar