回收器视图中的单选按钮单击出现问题



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

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

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

你需要试试这个。

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

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

最新更新