我在 settings.java 中有以下代码:
public static int numberOfQuestions = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(pref.getInt("NQ", 0)));
if(rbtn!=null)
rbtn.setChecked(true);
}
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
numbersBetween = 10;
break;
case R.id.rb_0to25:
numbersBetween = 25;
break;
case R.id.rb_0to50:
numbersBetween = 50;
break;
}
if(rg.getCheckedRadioButtonId() == R.id.rb_0to10 || rg.getCheckedRadioButtonId() == R.id.rb_0to25 || rg.getCheckedRadioButtonId() == R.id.rb_0to50)
{
savePref("NB", rg.getCheckedRadioButtonId());
}
}
这是保存和访问首选项的代码:
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
private void savePref(String key, Boolean value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
}
}
如果我在设置中 numberOfQuestions 变量得到更新,它在我的另一个名为 main.java 的视图中工作正常。但是可以说我直接打开 main.java 而不是打开设置第一个 numberOfQuestions 没有正确的值。有没有更简单的方法将共享偏好值转移到其他视图?还是我还需要在 main.java 中编写所有案例?