我目前正在開發一個具有菜單的應用程序,並且菜單中的一個選項是「設置」,用戶可以基本決定關閉聲音和其他類似的東西。我目前在設置活動中有兩個開關。下面是設置活動的Java代碼至今:Android保存在不同活動之間切換的值
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;
}
});
}
}
但是,如果我回到菜單活動,然後回到選項活動,開關的值返回到默認值。有沒有辦法在不同的活動之間保存狀態?謝謝!
檢查:HTTP://計算器.com/questions/24712821/sharedpreferemces-in-kitkat-version-in-android/24712877#24712877 – 2014-09-19 04:35:32