Petroslav Benchovsky
Petroslav Benchovsky

Reputation: 39

Click twice to check Radio Button?

I am trying to build a test application and I am using Radio buttons for the choices A,B,C,D. I am trying to calculate the result -> for example when press A increment 1, when press B increment 2 and so on. I was using Radio Group at first but I understood that if the user try to change the answer to his question from A to B the incremented result will be 3, not 2 as expected. So I switched to Radio Buttons and I try the following code:

      rb1.setOnCheckedChangeListener(new 
         android.widget.CompoundButton.OnCheckedChangeListener (){ 

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            i++;
            if(rb2.isChecked())
            { 
                i--;
                rb2.setChecked(false);                  
            }

        }
            });

    rb2.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener (){


        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            i++;

            if(rb1.isChecked())
            { 
                i--;
                rb2.setChecked(false);                          
            }
        }
            });

And now the second Radio Button have to be clicked twice in order to be checked. Is this a bug and could it be fixed. I need the Buttons to change state after the first click. All ideas and advice will be welcomed. Thank you.

Upvotes: 3

Views: 3418

Answers (1)

Dave
Dave

Reputation: 298

You can change your code to use a switch statement (as suggested in one of the comments) but if you want to continue with what you have, and to answer your question. In your code for rb2, you are saying that if rb1 is checked set rb2 to false. So, if you click rb1 (and it is now checked/pushed) and you click rb2 the first time you uncheck it, the 2nd time it stays checked.

So sticking with your coding style and procedure:

    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        i++;

        if(rb1.isChecked())
        { 
            i--;
            rb2.setChecked(false);                          
        }
    }

should be:

    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        i++;

        if(isChecked && rb1.isChecked())
        { 
            i--;
            rb1.setChecked(false);                          
        }

        rb2.setChecked(isChecked);
    }

Make a similar change to your rb1 method.

Upvotes: 1

Related Questions