Android radio button uncheck

A B picture A B · Apr 5, 2013 · Viewed 15.5k times · Source

The application is a step sequencer application with 16 radio groups with 8 buttons in each group. It works perfectly except once a group has a button selected I cant turn it off unless I use the clear button I have created to clear all radiogroups. What I would like to add is some code that says when a selected radio button is selected again it simply turns off like a toggle. I tried using toggles but then other issues arose with that method. Below are two attempts but both simply stops me using the button

final RadioGroup radioGroup1 = (RadioGroup) findViewById(R.id.RadioGroup1);
RadioButton D1 = (RadioButton) findViewById(R.id.RadioButtonD1);

Button D1 = (Button) findViewById(R.id.RadioButtonD1);
D1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick (View v){
        PdBase.sendFloat("D1", 74);
        int selectedTypeId = radioGroup1.getCheckedRadioButtonId();
        RadioButton D1 = (RadioButton) findViewById(selectedTypeId);
        if (D1 != null) // This will be null if none of the radio buttons are selected
            radioGroup1.clearCheck();
        PdBase.sendFloat("D1", 0);
    }
});

RadioButton lC1 = (RadioButton) findViewById(R.id.RadioButtonlowC1);
lC1.setOnClickListener(new View.OnClickListener() {
    public void onClick (View v) {
        int selectedTypeId = radioGroup1.getCheckedRadioButtonId();

        RadioButton lC1 = (RadioButton) findViewById(R.id.RadioButtonlowC1);
        if (selectedTypeId == -1) {
            PdBase.sendFloat("lC1", 72);
        }
        else if (selectedTypeId == R.id.RadioButtonlowC1) {
            radioGroup1.clearCheck();
            PdBase.sendFloat("lC1", 0);
        }
    }
});

Answer

spaaarky21 picture spaaarky21 · Mar 7, 2014

I recently had the same need - to have a radio group where the selected item could be deselected by tapping it again. I found that I couldn't accomplish that using listeners but I was able to do it using a custom RadioButton, like so...

public class ToggleableRadioButton extends RadioButton {
    // Implement necessary constructors

    @Override
    public void toggle() {
        if(isChecked()) {
            if(getParent() instanceof RadioGroup) {
                ((RadioGroup)getParent()).clearCheck();
            }
        } else {
            setChecked(true);
        }
    }
}

Notice that the button is toggled in different ways depending on its current state - i.e., calling setChecked(true) on the button vs. calling clearCheck() on the group. If setChecked() is used in both cases, a button that was just deselected cannot be immediately re-selected - the logic in RadioGroup seems to immediately deselect it.

To use this button, just replace your <RadioButton> tags with <your.package.ToggleableRadioButton> in your layout XML.