我的申请有问题。我只想设置2个复选框的限制,但我不知道如何。 我有4个复选框和一个按钮。按下按钮时,如果只有2个选中的复选框可以执行某些操作,如果是3个或更多则执行其他操作。这是我的代码:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(chk1.isChecked()){
counter++;}
else{
counter--;
}
if(chk2.isChecked())
{ counter++;}
else{
counter--;
}
if(chk3.isChecked())
{ counter++; }
else{
counter--;
}
if(chk4.isChecked())
{ counter++; }
else{
counter--;
}
if ( (chk1.isChecked() || chk2.isChecked() || chk3.isChecked() || chk4.isChecked()) && counter >2 ) {
Toast.makeText(StartingPoint.this, "boo", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(StartingPoint.this, "no boo", Toast.LENGTH_LONG).show();
}
}
});
答案 0 :(得分:0)
如果我理解正确,你几乎已经明白了。
counter
的值)修改 - 这是一个简化的示例。
/*
* This will check the number of CheckBoxes checked when your
* button is pressed, and perform some logic consequently.
*
* ALTERNATIVE (not shown here):
* If you wish to disable the button based on how many CheckBoxes
* are checked, you should add an OnClickListener for each CheckBox
* (I'm over-simplifying here on purpose).
* Each CheckBox click would increase the counter if checked,
* decrease it if not.
* Each listener would decide whether or not to enable the button
* after computing the counter's value.
*/
Button myButton = null; // TODO initialize properly
// TODO initialize all CheckBoxes properly
final CheckBox cb0 = null;
final CheckBox cb1 = null;
final CheckBox cb2 = null;
// ... and so forth ...
// Initializing the anonymous listener class attached to the Button
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// initializing the counter each click
int counter = 0;
// incrementing the counter for each CheckBox checked
if (cb0.isChecked()) counter++;
if (cb1.isChecked()) counter++;
if (cb2.isChecked()) counter++;
// ... and so forth ...
// Verifying number of CheckBoxes checked...
// ...up to 2 CheckBoxes checked
if (counter < 3) {
// TODO logic depending on which CheckBox(es)
}
// ...more than 2 CheckBoxes checked
else {
// TODO logic depending on which CheckBox(es) or anything else
}
}
});