I\'m writing an Activity in android where I have two radio buttons under a RadioGroup. One of them is checked by default. But I can\'t trigger the event in
Even though @dannys answer is ok I would like to have the default value taken from the XML layout definition file rather then setting it in code.
That's why I use this approach to:
OnCheckedChangeListenerThis could look like this in code with the first_radio_button as the default radio button:
// call this in any init method
_myRadioGroup = _myViewContainingTheRadioGroup.findViewById(R.id.my_radio_group);
int defaultValue = _myRadioGroup.getCheckedRadioButtonId();
_myRadioGroup.clearCheck();
_myRadioGroup.setOnCheckedChangeListener(_myRadioGroupCheckedChangeListener);
_myRadioGroup.check(defaultValue);
Place the OnCheckedChangeListener somewhere in your class:
private RadioGroup.OnCheckedChangeListener _myRadioGroupCheckedChangeListener = new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(group.findViewById(checkedId).getId())
{
case R.id.first_radio_button:
// do stuff
break;
case R.id.second_radio_button:
// do stuff
break;
// ...
}
}
};
This is my radio group xml
// ...