[英]How do I get my CheckBox to do something when it's checked?
例如,我有5個復選框(cb1-cb5)。 cb1優於其他cb1,這意味着只有同時檢查了其他所有4個才可以檢查它。 如果我檢查cb1,則所有其他4個應自動檢查。 這是我當前的Java代碼(此代碼在onCreate方法中):
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();
}
}
});
我是一個完整的初學者,因此代碼可能完全錯誤或只有一個小錯誤,我看不到它。 無論哪種方式,我都會感謝您的幫助。 另外,如果我的方法太復雜並且有更簡單的方法,請告訴我。
為復選框偵聽器創建一個類
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 ...
}
}
}
然后將此監聽器設置為所有復選框:
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.