How do I get my CheckBox to do something when it's checked?

一个人想着一个人 提交于 2020-01-06 14:28:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!