0

I want select only one radio button in recyclerView and get its data in its Activity.

I have gone through following solutions :

And I made one solution :

private static int lastCheckedPos = -1;

    binding.radioButton.setChecked(mImagesList.get(position).isSelected());
    binding.radioButton.setTag(new Integer(position));

                //for default check in first item
                if(position == 0 && mImagesList.get(0).isSelected() && binding.radioButton.isChecked())
                {
                    radioButton = binding.radioButton;
                    lastCheckedPos = 0;
                }

                binding.radioButton.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        RadioButton cb = (RadioButton)v;
                        int clickedPos = ((Integer)cb.getTag()).intValue();

                        if(cb.isChecked())
                        {
                            if(radioButton != null)
                            {
                                radioButton.setChecked(false);
                                mImagesList.get(lastCheckedPos).setSelected(false);
                            }

                            radioButton = cb;
                            lastCheckedPos = clickedPos;
                        }
                        else
                            radioButton = null;

                        mImagesList.get(clickedPos).setSelected(cb.isChecked());
                    }
                });

I have written this in onBindViewHolder method.

Now to get data i have written this in adapter :

public String getUserId() {

        if(lastCheckedPos == -1)
        {
            return null;
        } else {
            return mImagesList.get(lastCheckedPos).getUser_code();
        }
    }

And get this in activity :

 userId = adapter.getUserId();

But I am not able to get any data in activity. It is always showing null. Also if I click twice on radio button then it deselected.

Please ask if anything unclear. Any help would be appreciated.

Thank you :)

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
Annie
  • 2,397
  • 3
  • 18
  • 26

1 Answers1

2

Replace int clickedPos = ((Integer)cb.getTag()).intValue(); by int clickedPos =position;

Rajasekaran M
  • 2,478
  • 2
  • 20
  • 30