Search code examples
androidradio-buttonandroid-radiogroup

Change selection of radio group whenever a radio button is clicked


I have a custom radio group with two radio buttons inside it, what I want is to change its selection even if the user clicks on a checked radio button.

for now this is how it works:

enter image description here

as you see, if (off) is checked and I click on it, nothing happens.. I want it to change selection to (on).

I tried to use OnClickListener like this:

final RadioButton btn_on = view.findViewById(R.id.on);
    final RadioButton btn_off = view.findViewById(R.id.off);

    final View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                if(radio_group.getCheckedRadioButtonId()==R.id.on)
                {
                    radio_group.check(R.id.off);
                }

                if(radio_group.getCheckedRadioButtonId()==R.id.off)
                {
                    radio_group.check(R.id.on);
                }

        }
    };

    btn_on.setOnClickListener(listener);
    btn_off.setOnClickListener(listener);

but it won't work.. is there another way to do it?


Solution

  • I believe this should work:

    boolean fromClickListener = false;
    boolean fromCheckedChange = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        final RadioGroup radio_group = findViewById(R.id.radio_group);
        final RadioButton btn_on = findViewById(R.id.on);
        final RadioButton btn_off = findViewById(R.id.off);
    
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (fromClickListener)
                    return;
    
                fromCheckedChange = true;
            }
        });
    
    
        final View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fromCheckedChange) {
                    fromCheckedChange = false;
                    return;
                }
    
                boolean clickedOn = (((RadioButton) v) == btn_on);
    
                fromClickListener = true;
                btn_on.setChecked(!clickedOn);
                btn_off.setChecked(clickedOn);
                fromClickListener = false;
            }
        };
    
        btn_on.setOnClickListener(listener);
        btn_off.setOnClickListener(listener);
    }