之前做个一个投票应用,投票可以多选,但是又有上限,比如5选3,跟多选题一样。当时就写了个组合控件。
关键代码如下:
public void init(List<String> texts, int maxCheckedNum) {
setOrientation(VERTICAL);
this.maxCheckedNum = maxCheckedNum;
if (maxCheckedNum == 1) {
for (int i = 0; i < texts.size(); i++) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText(texts.get(i));
radioButton.setTag(i);
radioButton.setOnCheckedChangeListener(this);
addView(radioButton, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
} else {
for (int i = 0; i < texts.size(); i++) {
CheckBox checkBox = new CheckBox(getContext());
checkBox.setText(texts.get(i));
checkBox.setTag(i);
checkBox.setOnCheckedChangeListener(this);
addView(checkBox, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (maxCheckedNum == 1) {
if (isChecked) {
if (currentCheckedRadioButton != null) {
currentCheckedRadioButton.setChecked(false);
}
currentCheckedRadioButton = buttonView;
checkedPositions.clear();
checkedPositions.add((Integer) buttonView.getTag());
} else {
currentCheckedRadioButton = null;
checkedPositions.clear();
}
} else {
if (isChecked) {
if (checkedPositions.size() < maxCheckedNum) {
checkedPositions.add((Integer) buttonView.getTag());
} else {
Toast.makeText(getContext(), "You cann't select more!", Toast.LENGTH_SHORT).show();
buttonView.setChecked(false);
}
}