4

I have a radio button group in Android. I receive events when the items are selected. Normal so far. But I don't get the event if the user clicks on an already selected item. Is there a way to know (to receive an event) when the users hits a radiobutton either if it is selected or not? Thanks a lot.

Ton
  • 9,235
  • 15
  • 59
  • 103

2 Answers2

4

i don't understand why you would get an event when clicked on an already checked radio button, but if you want to unselect a radio button by a click on it if it is already selected!! check this code it can help you:

RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;

boolean hack = false;

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

    radioGroup = (RadioGroup) findViewById(R.id.rg);
    radioButton1 = (RadioButton) findViewById(R.id.r1);
    radioButton2 = (RadioButton) findViewById(R.id.r2);
    radioButton3 = (RadioButton) findViewById(R.id.r3);

    OnClickListener radioClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {       //The first codition check if we have clicked on an already selected radioButton
            if (v.getId() == radioGroup.getCheckedRadioButtonId() && hack)
            {
                radioGroup.clearCheck();
            }
            else
            {
                hack = true;
            }
        }
    };

    OnCheckedChangeListener radioCheckChangeListener = new OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            hack = false;
        }
    };

    radioButton1.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton2.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton3.setOnCheckedChangeListener(radioCheckChangeListener);

    radioButton1.setOnClickListener(radioClickListener);
    radioButton2.setOnClickListener(radioClickListener);
    radioButton3.setOnClickListener(radioClickListener);

} 
Hope this wil help
K_Anas
  • 31,226
  • 9
  • 68
  • 81
0

By setting an OnClickListener() on your buttons...

Sam
  • 86,580
  • 20
  • 181
  • 179
ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54