android - 在 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());
}
}
});
}
不知道它在哪里搞砸了任何逻辑。但我希望它以常规方式工作单选按钮的功能,但在回收站视图中。
解决方案
你需要试试这个。
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);
而已。现在您的单选按钮一次被选中,选择其他单选按钮将取消选择之前的选择。
推荐阅读
- java - 如何将 DefaultTableModel 对象的数据获取到 DefaultTableModel 的子类中
- python - 从公开的 Facebook 页面中删除帖子和评论
- elasticsearch - Elasticsearch Delete By Query API:Curl 正在工作,但无法使用 Python(请求)实现相同功能?
- html - HTML - 如何使文本垂直居中
- jquery - 我将如何将 jquery 实现到我现有的下拉列表中
- macos - Semaphore_create 导致内核恐慌
- vb.net - 在运行以下代码时,有什么方法可以修复错误,这将从 datagridview 生成 excel 文件?
- android - 如何通过 API instagram 获取所有 Instagram 帖子评论?
- android - 多个 RecyclerView 嵌套
- php - 更改`php.ini`中的值在Nginx中不生效