首页 > 解决方案 > Recyclerview 从单选按钮获取数据

问题描述

我只想选择一个单选按钮recyclerView并将其数据放在Activity.

我经历了以下解决方案:

我提出了一个解决方案:

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

我已经用onBindViewHolder方法写了这个。

现在要获取数据,我已将其写入adapter

public String getUserId() {

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

并在活动中得到这个:

 userId = adapter.getUserId();

但我无法获得任何活动数据。它总是显示为空。另外,如果我在单选按钮上单击两次,则取消选择。

请问有什么不清楚的。任何帮助,将不胜感激。

谢谢 :)

标签: androidandroid-recyclerviewandroid-adapterandroid-radiobutton

解决方案


替换int clickedPos = ((Integer)cb.getTag()).intValue();int clickedPos =position;


推荐阅读