Monday, February 9, 2009

Using a RadioGroup

Set up your RadioGroup and RadioButtons in your xml layout:


<radiogroup id="@+id/group1" layout_width="fill_parent" layout_height="wrap_content" orientation="horizontal">
<radiobutton id="@+id/radio1" text="Bell" layout_width="wrap_content" layout_height="wrap_content">
</radiobutton>
<radiobutton id="@+id/radio2" text="Crystal" layout_width="wrap_content" layout_height="wrap_content">
</radiobutton>
<radiobutton id="@+id/radio3" text="Gong" layout_width="wrap_content" layout_height="wrap_content">
</radiobutton>
</radiogroup>


Save your preferences


int chime = chimes.getCheckedRadioButtonId();


At first nothing is selected and getCheckedRadioButtonId will return a value of -1, so you might want to test for this condition when getting your saved preferences. Otherwise you'll get the Unique ID of the checked Radio Button which you need to test using R.id.


int chime = prefs.getInt(PREF_CHIME, R.id.radio1);
if (chime < 1)
chime = R.id.radio1;
chimes.check(chime);


Handle the options:


int chime = prefs.getInt(preferences.PREF_CHIME, R.raw.bell);
switch(chime){
case R.id.radio1: {
mp = MediaPlayer.create(timer.this, R.raw.bell);
break;
}
case R.id.radio2: {
mp = MediaPlayer.create(timer.this, R.raw.crystal);
break;
}
case R.id.radio3: {
mp = MediaPlayer.create(timer.this, R.raw.gong);
break;
}
default:
mp = MediaPlayer.create(timer.this, R.raw.bell);
break;
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

No comments:

Post a Comment