如何用RecyclerView android选择一个RadioButton?

hos*_*kha 1 android radio-button android-recyclerview

我有一个带RadioButton的RecyclerView我只想在同一时间选择一个RadioButton并且我的代码使它工作正常,但当我从上到下重复选择时,选择消失我怎么能修复它,谢谢.

在此输入图像描述

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;


        }
    });
Run Code Online (Sandbox Code Playgroud)

小智 8

您不需要使用 保留位置Tag或使用 重新加载列表notifyDataSetChanged()。只需使用checkedRadioButton并切换它即可。然后您可以使用checkedRadioButton来获取所选项目。

private var checkedRadioButton: CompoundButton? = null

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemView.radio_button.setOnCheckedChangeListener(checkedChangeListener)
    if (holder.itemView.radio_button.isChecked) checkedRadioButton = holder.itemView.radio_button
}

private val checkedChangeListener = CompoundButton.OnCheckedChangeListener { compoundButton, isChecked ->
    checkedRadioButton?.apply { setChecked(!isChecked) }
    checkedRadioButton = compoundButton.apply { setChecked(isChecked) }
}
Run Code Online (Sandbox Code Playgroud)


San*_*mar 7

你可以这样做,使用RadioButton我只是写而不检查但这是一个暗示 -

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

    }
});
Run Code Online (Sandbox Code Playgroud)