首页 > 解决方案 > 在 recyclerview 中单击单选按钮时出现问题

问题描述

因此,在我的情况下,我在 recyclerview 中使用单选按钮按照此链接进行单击功能。它的工作几乎正常。只面临一个问题,当您尝试在 recyclerview 的第一项上点击两次时,即使您之后尝试点击任何其他项目,它也始终保持正确。下面是我试图实现的逻辑。

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

不知道它在哪里搞砸了任何逻辑。但我希望它以常规方式工作单选按钮的功能,但在回收站视图中。

标签: androidandroid-recyclerviewradio-button

解决方案


你需要试试这个。

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

而已。现在您的单选按钮一次被选中,选择其他单选按钮将取消选择之前的选择。


推荐阅读