在RecyclerView中取消选中选中的单选按钮

时间:2018-10-24 09:46:38

标签: android android-recyclerview recycler-adapter

我要在第二次单击时取消选中选中的单选按钮(这是一个单选单选按钮代码)

下面是我的代码:

int row_index = -1;

holder.rbBookOfferText.setOnClickListener(view -> {
        holder.rbBookOfferText.setChecked(true);

        row_index = Integer.parseInt(mDataset.get(position).getTaskId());
        notifyDataSetChanged();

    });

    if (row_index == Integer.parseInt(mDataset.get(position).getTaskId())) {
        holder.rbBookOfferText.setChecked(true);
    } else {
        holder.rbBookOfferText.setChecked(false);
    }

enter image description here

3 个答案:

答案 0 :(得分:2)

您必须在第一次点击时以编程方式设置 holder.rbBookOfferText.setChecked(true); 。因此, rbBookOfferText 不会在首次点击时取消选中。

答案 1 :(得分:0)

要在第二次单击同一单选按钮时取消选中单选按钮,您需要将所有单选按钮归入一个单选组

    <?xml version="1.0" encoding="utf-8"?>
    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Place 3 order of Margherita and on 4th order get $20 off"
            android:onClick="onRadioButtonClicked"/>
       <RadioButton android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hourly based order"
            android:onClick="onRadioButtonClicked"/>
      <RadioButton android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Place 3 order of Pugliese and get 4th Pugliese free"
            android:onClick="onRadioButtonClicked"/>
      <RadioButton android:id="@+id/radio4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="40% order off on Place order "
            android:onClick="onRadioButtonClicked"/>
    </RadioGroup>

答案 2 :(得分:0)

我得到了答案;

    holder.tvBookOfferText.setOnClickListener(view -> {

            if (mDataset.get(position).getTaskId().equalsIgnoreCase(String.valueOf(row_index))) {
                holder.tvBookOfferText.setChecked(false);
                row_index = -1;
            } else {
                holder.tvBookOfferText.setChecked(true);
                row_index = Integer.parseInt(mDataset.get(position).getTaskId());
                notifyDataSetChanged();
            }

        });

        if (row_index == Integer.parseInt(mDataset.get(position).getTaskId())) {
            holder.tvBookOfferText.setChecked(true);
        } else {
            holder.tvBookOfferText.setChecked(false);
        }
相关问题