我一直试图在其他activites中使用/保存复选框的布尔值,但没有多少运气。在其他Activites中使用CheckBox值Android
我知道你必须使用SharedPreferences,但是我无法正确设置它。我已经做了首类具有
private static final String OPTION_PREF = "my.main.project";
private SharedPreferences optionPreferences;
private Editor optionEditor;
private boolean checkbox;
public Preferences(Context context)
{
this.optionPreferences = context.getSharedPreferences(OPTION_PREF, Activity.MODE_PRIVATE);
this.optionEditor = optionPreferences.edit();
}
public boolean getChecked()
{
return optionPreferences.getBoolean("is_checked", checkbox);
}
public void saveChecked(boolean checkBox)
{
optionEditor.putBoolean("save_check_pref", checkBox);
optionEditor.commit();
}
然后在例如选项菜单,
boolean veggieChecked;
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
Preferences pref;
pref = new Preferences(getApplicationContext());
veggieChecked = pref.getChecked();
final CheckBox checkBox = (CheckBox) findViewById(R.id.vegetarian);
if(checkBox.isChecked())
veggieChecked = true;
pref.saveChecked(veggieChecked);
我真的不能看到我在做什么错了,因为我是新来的Android和没有使用sharedpreferences之前..任何帮助将不胜感激!
如果你想使用'SharedPreferences',你需要调用'Context.getSharedPreferencs()'再在选项菜单,然后调用'得到() ',而不是做'checkbox.isChecked()'。 – gobernador 2012-03-24 15:04:05