问题描述
如何限制android中已选中复选框的数量?我有多个以编程方式添加的复选框,很难跟踪它们。
final CheckBox currentvariantCheckBox = new CheckBox(getApplicationContext());
checkBoxGroupList.add(currentvariantCheckBox);
Log.d(TAG,"onDataChange: added " + currentvariantCheckBox + " to the checkBoxgrouplist; size = " + checkBoxGroupList.size());
currentvariantCheckBox.setChecked((Boolean) currentvariant.child("checked").getValue());
LinearLayout checkBoxGroupLayout = new LinearLayout(getApplicationContext());
checkBoxGroupLayout.setorientation(LinearLayout.HORIZONTAL);
currentvariantCheckBox.setText(currentvariant.child("name").getValue(String.class));
TextView currentvariantPriceTag = new TextView(getApplicationContext());
checkBoxGroupLayout.addView(currentvariantCheckBox);
if (currentvariant.child("price").exists()) {
currentvariantPriceTag.setText("+" + currentvariant.child("price").getValue(float.class).toString() + " €");
checkBoxGroupLayout.addView(currentvariantPriceTag);
解决方法
好的,所以我没有使用onCheckedStateChangedLister,而是使用了OnClickListener。我创建了一个ArrayList来跟踪所有选中的复选框:
final ArrayList<CheckBox> checkedList = new ArrayList<>();//this is the list to keep track of checked checkboxes
int maxOptions = 3
int minOptions = 1
currentVariantCheckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Boolean currentCheckState = currentVariantCheckbox.isChecked();
if (currentCheckState) {//if the clicked checkboxes was unchecked and is now checked
checkedList.add(currentVariantCheckbox);
Log.d(TAG,"onClick: added " + currentVariantCheckbox + " ;checkedList.size is now: " + checkedList.size());
if (checkedList.size() >= maxOptions) {
checkedList.get(0).setChecked(false);
checkedList.remove(0);// if limit exceeded remove the first element from the checked list
Log.d(TAG,"onCheckedChanged: checkedList's size is now: " + checkedList.size());
}
} else if (checkedList.size() <= minOptions) {
currentVariantCheckbox.setChecked(true);
// if the list is empty just add the clicked checkbox to the list for example here 0
// and it will be checked automatically
} else {
checkedList.remove(currentVariantCheckbox);
// if the checkbox was already checked and no limit is exceeded
// then it will be unchecked therfore it should be removed from checkedList
}
}
});