Android Check box Group

56,234

Solution 1

You could use Radio Buttons and set up different groups of them.

This documentation and This tutorial should help you out if you find that Radio Buttons are the way to go.

Solution 2

Here is what I did. Not sure if this will work for you but its something you could use as a start. My check boxes I don't need any on check listeners, but you could add them to each one if you'd like

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private CheckBox chk1, chk2, chk3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    chk1 = (CheckBox) findViewById(R.id.checkbox1);
    chk2 = (CheckBox) findViewById(R.id.checkbox2);
    chk3 = (CheckBox) findViewById(R.id.checkbox3);
    if (chk1.isChecked()) {
        chk1.setChecked(false);
    }
        else if(chk2.isChecked()){
          chk2.setChecked(false);
         }
    else {
        chk3.setChecked(false);
    }
    chk1.setOnClickListener(this);
    chk2.setOnClickListener(this);
    chk3.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
    switch(view.getId()){
        case R.id.checkbox1:
        chk1.setChecked(true);
        chk2.setChecked(false);
        chk3.setChecked(false);
        break;
        case R.id.checkbox2:
        chk2.setChecked(true);
        chk3.setChecked(false);
        chk1.setChecked(false);
        break;
        case R.id.checkbox3:
        chk3.setChecked(true);
        chk2.setChecked(false);
        chk1.setChecked(false);
        break;
    }
    }
}
Share:
56,234
Mohamed Sobhy
Author by

Mohamed Sobhy

A total geek, an Android addict (with a bit of a Google crush), wannabe Hacker & a Gadgets freak

Updated on March 19, 2021

Comments

  • Mohamed Sobhy
    Mohamed Sobhy over 3 years

    I'm trying to apply some kind of validation on a group of check boxes (e.g. Two contradictory items cannot be checked together) so I want to somehow group Check Box objects and apply something like RequiredFieldValidator on the whole group once and in that validator I will register listeners and do the whole check on my Check Boxes objects.

    What I imagine would be a code that look like that:

    CheckBoxView allMyCheckBoxes = new CheckBoxView(checkbox1,checkbox2,checkbox3); //varargs
    validate(allMyCheckBoxes);
    

    Validate will contain the logic of contradictory check boxes and everything.

    Is that already implemented somewhere in Android? If not, anybody tried out something like that? (Hopefully share it with us here)