如何使用 RecyclerView android 只选择一个 RadioButton?如何使用、RecyclerView、RadioButton、android

2023-09-06 19:29:39 作者:把你的名写在烟上吸进肺里

我有一个带有 RadioButton 的 RecyclerView 我只想同时选择一个不多的 RadioButton,我的代码使它工作正常,但是当我从上到下重复选择时,选择消失了我该如何修复它,谢谢.

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.

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;


        }
    });

推荐答案

你可以这样做,使用 RadioButton 我只是写了没有检查但这是给你的一个提示 -

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;
        }

    }
});