我有以下代码:
这是在 onCreate - 我正在尝试在此处设置单选按钮的默认值,这将是单选按钮上的预选值。
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
int selectedOption = rg_numberOfQuestions.getCheckedRadioButtonId();
rb_NumberOfQuestions = (RadioButton) findViewById(selectedOption);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
final RadioGroup rg_numbersBetween = (RadioGroup) findViewById(R.id.radioGroupNumbersBetween);
selectedOption = rg_numbersBetween.getCheckedRadioButtonId();
rb_NumbersBetween = (RadioButton) findViewById(selectedOption);
rg_numbersBetween.setOnCheckedChangeListener(this);
@Override
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
savePref("rb_0to10", rg.getCheckedRadioButtonId());
break;
case R.id.rb_0to25:
savePref("rb_0to25", rg.getCheckedRadioButtonId());
break;
case R.id.rb_0to50:
savePref("rb_0to50", rg.getCheckedRadioButtonId());
break;
case R.id.rb_15:
savePref("rb_15", rg.getCheckedRadioButtonId());
break;
case R.id.rb_25:
savePref("rb_25", rg.getCheckedRadioButtonId());
break;
case R.id.rb_50:
savePref("rb_50", rg.getCheckedRadioButtonId());
break;
}
}
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
上面的代码在第一次获得第一个单选按钮的默认值时工作。但无论我选择什么其他单选按钮,它都不起作用,它没有保存按钮点击值,它总是获得第一个单选按钮。