问题
For example, I have 5 checkboxes (cb1 - cb5). cb1 is superior to others, which means it can only be checked if all the other 4 are checked. And if I check cb1, all the other 4 should automatically get checked. This is my current java code (this code is within onCreate method):
final CheckBox cb1 = (CheckBox) findViewById(R.id.checkBox1);
final CheckBox cb2 = (CheckBox) findViewById(R.id.checkBox2);
final CheckBox cb3 = (CheckBox) findViewById(R.id.checkBox3);
final CheckBox cb4 = (CheckBox) findViewById(R.id.checkBox4);
final CheckBox cb5 = (CheckBox) findViewById(R.id.checkBox5);
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( cb1.isChecked() )
{
cb2.isChecked();
cb3.isChecked();
cb4.isChecked();
cb5.isChecked();
}
}
});
I'm a complete beginner so the code may be completely wrong or there's just a small error and I can't see it. Either way, I'd appreciate the help. Also, if my way is too complicated and there's an easier way, let me know please.
回答1:
Create a class for checkbox listener
public class CheckBoxListener implements OnCheckedChangeListener {
public CheckBoxListener() {
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
switch(view.getId()) {
case R.id.checkBox1:
//do something
case R.id.checkBox2:
case ...
}
}
}
Then set this listener to all your checkboxes:
final CheckBox cb1 = (CheckBox) findViewById(R.id.checkBox1);
final CheckBox cb2 = (CheckBox) findViewById(R.id.checkBox2);
final CheckBox cb3 = (CheckBox) findViewById(R.id.checkBox3);
final CheckBox cb4 = (CheckBox) findViewById(R.id.checkBox4);
final CheckBox cb5 = (CheckBox) findViewById(R.id.checkBox5);
cb1.setOnCheckedChangeListener(new CheckBoxListener());
cb2.setOnCheckedChangeListener(new CheckBoxListener());
cb3.setOnCheckedChangeListener(new CheckBoxListener());
cb4.setOnCheckedChangeListener(new CheckBoxListener());
来源:https://stackoverflow.com/questions/17050666/how-do-i-get-my-checkbox-to-do-something-when-its-checked