禁用复选框后,检查一定数量的复选框
问题描述:
我有6个复选框,我想例如,如果我有一个变量a = 2让用户检查2复选框,并使其他禁用..如果我有一个= 3让用户检查3个复选框和禁用休息等on..This是我的尝试:禁用复选框后,检查一定数量的复选框
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
check1=(CheckBox)findViewById(R.id.check1);
check2=(CheckBox)findViewById(R.id.check2);
check3=(CheckBox)findViewById(R.id.check3);
check4=(CheckBox)findViewById(R.id.check4);
check5=(CheckBox)findViewById(R.id.check5);
check6=(CheckBox)findViewById(R.id.check6);
if(a==1)
{
only one can be checked the others get disabled
}
}
}
和XML文件的一部分:
<CheckBox android:id="@+id/check1"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="@layout/cb_selector"
android:layout_marginLeft="80dp"
android:layout_marginTop="505dp"
android:onClick="itemClicked"
/>
<CheckBox android:id="@+id/check2"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="@layout/cb_selector"
android:layout_marginLeft="365dp"
android:layout_marginTop="505dp"
/>
我怎样才能实现这一目标?
答
您需要一个复选框和您在onCheckedChange中检查变量的数组。
CheckBox[] cba;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cba = new CheckBox[]{
(CheckBox)findViewById(R.id.check1),
(CheckBox)findViewById(R.id.check2),
(CheckBox)findViewById(R.id.check3),
(CheckBox)findViewById(R.id.check4),
(CheckBox)findViewById(R.id.check5),
(CheckBox)findViewById(R.id.check6)
};
//here set onChechedChange for all your checkboxes
for (CheckBox cb:cba) {
cb.setOnCheckedChangeListener(cbListener);
}
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkEnoughAndMakeDisabled(cba);
}
};
private void checkEnoughAndMakeDisabled(CheckBox checkBoxes[]){
int countChecked =0;
for (CheckBox cb:checkBoxes){
cb.setEnabled(true);
if (cb.isChecked()) countChecked++;
}
//your variable
if (a <= countChecked) {
for (CheckBox cb:checkBoxes){
if (!cb.isChecked())cb.setEnabled(false);
}
}
}
PS:另外我想对于这样的问题,最好的做法是Data-Binding使用,但它是另外一个故事
它给了我在onCheckedChange –
的CB错误忘了数组来设置监听器,见编辑答案 – Beloo
血腥天才!谢啦! –