我是java新手,我不明白如何完全阅读代码,所以这可能是一个重复的问题。我想保存一个 boolean 状态,以便当用户退出或启动应用程序时, boolean 将等于相同的值。我想将值保存在一项 Activity 中,而不是在另一项 Activity 中使用它。我找到了引用
saving boolean preference problem
但我不明白文档。我想保存类似于intent.setExtra的值,但我希望即使应用程序关闭也能保存它。
最佳答案
用于优先保存 boolean 值。
public static void saveBoolean(String key, boolean value)
{
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
用于从偏好中获取 boolean 值。
public static boolean getBoolean(String key)
{
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
希望对您有帮助。
关于java - 保存 boolean 值并在 Activity 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20769588/