如何检查CheckBox是否可以执行某些操作?

时间:2013-06-11 17:59:27

标签: java android eclipse checkbox checked

例如,我有5个复选框(cb1 - cb5)。 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();
        }
    }
});

我是一个完全的初学者,所以代码可能完全错误或只是一个小错误,我看不到它。无论哪种方式,我都很感激帮助。此外,如果我的方式太复杂而且方法更简单,请告诉我。

1 个答案:

答案 0 :(得分:0)

为复选框侦听器

创建一个类
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());