如何存储使用共享preferences在Android的一个布尔值?布尔值、preferences、Android

2023-09-13 23:59:22 作者:轻言的做作。

我要救布尔值,然后在if-else块进行比较。

我目前的逻辑是:

 布尔锁定= TRUE;

  如果(锁定==真){
                SETBoolean为FALSE
                }
            其他 {
            意图newActivity4 =新的意图(parent.getContext()
            Tag1.class);
    startActivity(newActivity4);

        }
 

如何保存已经被设置为false布尔变量?

解决方案

 共享preferences preFS = preferenceManager.getDefaultShared preferences();
prefs.edit()putBoolean(锁定,真).commit()。
 

让他们回到使用

 布尔yourLocked = prefs.getBoolean(锁定,假);
 
Android Preferences的使用

而假的是默认值失败或未设置时,

在你的code就应该是这样的:

 布尔锁定= TRUE;
共享preferences preFS = preferenceManager.getDefaultShared preferences();
如果(锁定){
//也许你想要得到的共享preferences进行检查。使用此,而是如果(锁定)
//如果(prefs.getBoolean(锁定,锁定){
   prefs.edit()putBoolean(锁定,真).commit()。
} 其他 {
   startActivity(新意图(parent.getContext(),Tag1.class));
}
 

I want to save boolean values and then compare them in an if-else block.

My current logic is:

boolean locked = true;

  if (locked == true) { 
                SETBoolean TO FALSE
                } 
            else {
            Intent newActivity4 = new Intent(parent.getContext(),
            Tag1.class);
    startActivity(newActivity4);

        }

How do I save the boolean variable which has been set to false?

解决方案

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
prefs.edit().putBoolean("locked", true).commit();

to get them back use

Boolean yourLocked = prefs.getBoolean("locked", false);

while false is the default value when it fails or is not set

In your code it would look like this:

boolean locked = true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
if (locked) { 
//maybe you want to check it by getting the sharedpreferences. Use this instead if (locked)
// if (prefs.getBoolean("locked", locked) {
   prefs.edit().putBoolean("locked", true).commit();
} else {
   startActivity(new Intent(parent.getContext(), Tag1.class));
}