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:
- store the default value form the radio group
- clear all check's
- initialize the
OnCheckedChangeListener
- check the default again (which was stored previously) which triggers the listener
This 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
<RadioGroup
android:id="@+id/my_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/first_radio_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true"
android:text="@string/first_radio_button_text"/>
<RadioButton
android:id="@+id/second_radio_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/second_radio_button_text"/>
// ...
</RadioGroup>
performClick()
code after you set thelistener
– Readylistener
to be sure that it isn't going there and something else inside it isn't screwing it up? – Ready