0

So, I followed this link for single click functionality using a radio button in my case inside a recyclerview. Its working almost fine. Only facing one issue, is when you try tapping twice on the first item of recyclerview, it always stays true even though you try hitting any other item after that. Below is the logic which I tried to implement.

private List<Profile> profileList;
private Context context;
private RadioButton lastChecked = null;
private int lastCheckedPos = 0;

public void onBindViewHolder(@NonNull MyHolder holder, int position) {
    Profile profile = profileList.get(position);
    holder.imgRadioButton.setChecked(profile.isSelected());
    holder.imgRadioButton.setTag(position);

    holder.imgRadioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int clickpos = (Integer) holder.imgRadioButton.getTag();

            if (lastCheckedPos != clickpos) {
                if (holder.imgRadioButton.isChecked()) {

                    if (lastChecked != null) {
                        lastChecked.setChecked(false);
                        profileList.get(lastCheckedPos).setSelected(false);
                    }

                    lastChecked = holder.imgRadioButton;
                    lastCheckedPos = clickpos;

                } else {

                    lastChecked = null;

                }
                profileList.get(clickpos).setSelected(holder.imgRadioButton.isChecked());
            }
        }
    });
}

Dont know where its messing up any logic. But I want it to work in a regular way how radio button functions, but in a recyclerview.

Darpal
  • 352
  • 5
  • 20

1 Answers1

0

You need to try this.

Add   lastChecked.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    lastCheckededPos = getAdapterPosition();
                    notifyDataSetChanged();
                }
            });

to the ViewHolder() constructor.
Then use this in onBindViewHolder() method:

      // this condition un-checks previous selections
        holder.lastChecked.setChecked(lastCheckedPos == position);

That's it. Now your radio button is selected One at a time and selecting other radio button will un-select previous selection.