'How to get CheckBox value present in RadioGoup in Android?

New to Android, I am creating a question Answer App. So I want to get the value of checkBoxes. I know how to get value of radio button present in Radio Group. But I want to know is it good practice to keep checkBixes in RadioGroup and how to get the Checkboxes value?



Solution 1:[1]

What do you mean by getting CheckBox value? You can get the state (checked or not checked) and you can also get the text label for the CheckBox itself (getText()).

As for keeping them in a RadioGroup, it will depend largely on your use case (when grouped, the user might expect that only one CheckBox at the time can be checked). If you were to implement RadioGroup, you will have to implement a listener and then determine which CheckBox was checked. For that you can look at the accepted answer on this closely related question here.

Here is how you can get the Text of the CheckBox that was checked/unchecked:

@Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        CheckBox checkBox = (CheckBox)findViewById(checkedId); 
       //here you can check if it was checked or not, including the text
       String text = checkBox.getText().toString();
       boolean isChecked = checkBox.isChecked();
    }

I hope this sheds some light.

Solution 2:[2]

Unfortunately as you would expect to utilize radioGroup's getCheckedRadioButtonId() for radio buttons, there is no such thing for check boxes. There are many ways to do this but I think the simplest and cleanest way would be the following:

For CheckBoxes

// Define one listener to use it for all of your CheckBoxes:
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       // You can also use the buttonView.isChecked() instead of isChecked parameter too : if(ButtonView.isChecked)..
       if(isChecked) {
           // Do stuff with this checkBox for example:
           String stringToShow = buttonView.getText();
         }
      }
    };
// Reference your CheckBoxes to your xml layout:
CheckBox checkBox1 = findViewById(R.id.checkBox1);
CheckBox checkBox2 = findViewById(R.id.checkBox2);
// and many more check boxes..
        
/* Set the above listener to your Check boxes so they would
notify your above piece of code in case their checked status 
changed:*/
checkBox1.setOnCheckedChangeListener(listener);
checkBox2.setOnCheckedChangeListener(listener);
// and many more check boxes..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Araz