正如标题所述,我需要使单选按钮一次只能选择1个。
这是我的适配器:
public class NewGameCourseAdapter extends RecyclerView.Adapter<NewGameCourseAdapter.NewGameCourseViewHolder> {
private ArrayList<NewGameCourseItem> mCourseList;
private NewGameCourseAdapter.OnItemsCheckStateListener checkStateListener;
private int checkedItems = 0;
public void setOnItemsCheckStateListener(OnItemsCheckStateListener checkStateListener2) {
this.checkStateListener = checkStateListener2;
}
public interface OnItemsCheckStateListener {
void onItemCheckStateChanged(int checkedItemCounter);
}
onBindViewHolder:
@Override
public void onBindViewHolder(@NonNull final NewGameCourseViewHolder holder, final int position) {
final NewGameCourseItem currentItem = mCourseList.get(position);
/** This can prevent some unwanted actions in some cases **/
holder.mRadioButton.setOnCheckedChangeListener(null);
/** If true, radio button will be selected, else unselected **/
holder.mRadioButton.setChecked(currentItem.getRadioButton());
holder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
/** set object's last status **/
currentItem.setSelected(isChecked);
if (isChecked) {
checkedItems++;
} else {
checkedItems--;
}
checkStateListener.onItemCheckStateChanged(checkedItems);
}
});
我使用了与巫婆复选框相同的方法,并且我认为也许我也可以对此进行一些改动。 为了使单个选择在这里工作,我应该做什么/更改? 如何使其更改先前的选择为假?
答案 0 :(得分:0)
您可以使用选定的按钮存储项目的位置并更新其状态(通过更改数据列表元素中的布尔值,然后在单击另一个按钮时调用notifyItemChanged(position)
。并更新该位置毕竟,当然
答案 1 :(得分:0)
使用arrayList传递的数据
//final List<CheckBox> allChkBoxes = new ArrayList<>();
//allChkBoxes.add(holder.chkBox);
holder.chkBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
for(int i =0 ; i < arryList.size(); i ++){
//The postion which you get on OnClick is compared with all CheckBoxes added to List
if(i == position){
holder.chkBox.setChecked(true);
}else {
holder.chkBox.setChecked(false); //Clear check
}
}
}
}
);