Android: RadioGroup - How to configure the event listener

Solution 1:

This is how you get the checked radiobutton:

// This will get the radiogroup
RadioGroup rGroup = (RadioGroup)findViewById(r.id.radioGroup1);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());

To use the listener, you do this:

// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        // This will get the radiobutton that has changed in its check state
        RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
        // This puts the value (true/false) into the variable
        boolean isChecked = checkedRadioButton.isChecked();
        // If the radiobutton that has changed in check state is now checked...
        if (isChecked)
        {
            // Changes the textview's text to "Checked: example radiobutton text"
            tv.setText("Checked:" + checkedRadioButton.getText());
        }
    }
});

Solution 2:

It should be something like this.

RadioGroup rb = (RadioGroup) findViewById(R.id.radioGroup1);
rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {

            }
        }

    });

Based on the checkedId, you would know which of the radiobutton has been clicked and then use your above code to figure out if its checked or unchecked. This is homework. ;)

Solution 3:

Using Switch is better:

radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup arg0, int id) {
        switch (id) {
        case -1:
          Log.v(TAG, "Choices cleared!");
          break;
        case R.id.chRBtn:
          Log.v(TAG, "Chose Chicken");
          break;
        case R.id.fishRBtn:
          Log.v(TAG, "Chose Fish");
          break;
        case R.id.stkRBtn:
          Log.v(TAG, "Chose Steak");
          break;
        default:
          Log.v(TAG, "Huh?");
          break;
        }
      }
    });