0

I have a simple program that has 3 radio buttons in a group. When I click on any of the radio buttons I have a Toast appear to let the user know which button they have selected.

My problem I am facing is I have a onClick event for a button that clearCheck the radio group. When that happens, the Toast message appears again with the previous selected information from the radio button.

How do I prevent the toast from happening when I clearCheck the radio group?

public class MainActivity extends AppCompatActivity {

    RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Radio Group and attach click handler
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.clearCheck();

        // Attach CheckedChangeListener to Radio Group
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                if(null!=rb && checkedId > -1){
                    Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void onClear(View v){
        // Clears the radio buttons when the clear button is pressed
        radioGroup.clearCheck();
    }
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
user2683183
  • 243
  • 2
  • 7
  • 23

1 Answers1

-1

That is because clearing the check is changing the checked status of the radio group. You need to set a flag to let the listening know it should ignore that change.

Just a simple boolean declared in the class, flagged in onClear and checked in onCheckChanged (and reset the flag in onCheckChanged also).

Knossos
  • 15,802
  • 10
  • 54
  • 91
  • onCheckedChanged: "Called when the checked radio button has changed. When the selection is cleared, checkedId is -1" this check `if(null!=rb && checkedId > -1){` should prevent toast showing. You extra flag will work but it's not a solution of a problem. – dilix Jan 13 '16 at 14:30