【问题标题】:Having an issue with radio button click in recyclerview在 recyclerview 中单击单选按钮时出现问题
【发布时间】:2020-05-26 03:34:17
【问题描述】:

因此,在我的情况下,我在 recyclerview 中使用单选按钮遵循了这个 link 的单击功能。它的工作几乎正常。只面临一个问题,当您尝试在 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());
            }
        }
    });
}

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

【问题讨论】:

    标签: android android-recyclerview radio-button


    【解决方案1】:

    你需要试试这个。

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

    就是这样。现在您的单选按钮一次被选中,选择其他单选按钮将取消选择之前的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2015-01-04
      • 2011-03-09
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      相关资源
      最近更新 更多