Search code examples
androidradio-buttonradio-groupandroid-radiogroup

(Android) RadioButton: resetting event if unselected?


As practice, I'm making this very simply app that allows users to answer a few questions to decide if they prefer dogs or cats. I use dogCounter and catCounter int variables to count how many answers are pro-dog or pro-cat.

I have one question that asks: Which animal is the cutest?

If they select "dogs", for instance, the app adds 1 to dogCounter. But if they later decide to select "cats" instead, dogCounter's value remains the same (which is 1). I'm trying to make it so that if "dogs" is unselected after previously being selected, dogCounter will revert back to 0.

I'm not sure what to do after this:

public void setCutestQuestion3(RadioGroup radioGroup) {
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            radioButtonCutest = (RadioButton) findViewById(checkedId);

            if (radioButtonCutest != null) {

                if (radioButtonCutest.getText().equals("Dogs")) {
                    dogCounter += 1;

                } else if (radioButtonCutest.getText().equals("Cats")) {
                    catCounter += 1;
                }
            }
        }
    });
}

Could someone please help? I'm embarrassed to say that I've spent two days trying to figure this out.

Thanks in advance.


Solution

  • If I understand correctly, for every question you two answers that determine if the user prefers cat or dog is thaht correct ? In that case, unselect dog also means select cat:

    public void setCutestQuestion3(RadioGroup radioGroup) {
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
    
            radioButtonCutest = (RadioButton) findViewById(checkedId);
    
            if (radioButtonCutest != null) {
    
                if (radioButtonCutest.getText().equals("Dogs")) {
                    dogCounter += 1;
                    catCounter -= 1
    
                } else if (radioButtonCutest.getText().equals("Cats")) {
                    catCounter += 1;
                    dogCounter -= 1;
                }
            }
        }
    });
    }
    

    Hope it helped