我目前正在开发一个具有菜单的应用程序,菜单上的一个选项是“设置”,用户基本上可以决定关闭声音和其他类似的东西。我目前在“设置”活动中有两个开关。以下是目前为止设置活动的java代码:
public class Options extends ActionBarActivity {
private Switch ding;
private Switch countdown;
public boolean isDingChecked;
public boolean isCountdownChecked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
ding = (Switch) findViewById(R.id.switch1);
AppPreferences appPref;
appPref = new AppPreferences(getApplicationContext(), "PREFS");
appPref.SaveData("Value", "Tag");
appPref.getData("state");
if(appPref.getData("state").equals("true"))
{
ding.setChecked(true);
}
else if(appPref.getData("state").equals("false"))
{
ding.setChecked(false);
}
ding.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(ding.isChecked())
{
ding.setChecked(true);
}
}
});
countdown = (Switch) findViewById(R.id.switch2);
countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
isCountdownChecked = isChecked;
}
});
}
}
但是,如果我返回菜单活动然后返回选项活动,则交换机的值将恢复为默认值。有没有办法可以在不同的活动之间保存状态?谢谢!
答案 0 :(得分:3)
您可以使用SharedPreferences。
存储它:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("StringName", "StringValue");
// Commit the edits!
editor.commit();
恢复它:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
String silent = settings.getString("StringName", "DefaultValueIfNotExists");
你也可以放置和恢复布尔和整数以及其他...... http://developer.android.com/reference/android/content/SharedPreferences.html