【问题标题】:Shared Prefs with a Boolean使用布尔值共享首选项
【发布时间】:2019-01-09 10:36:43
【问题描述】:

我想使用 sharedPrefs 保存一个简单的设置或更布尔值。如果用户单击“按钮”,则 button2 应该更改其 alpha。但是,如果我关闭应用程序,0.25f 的 alpha 值将消失,并且 button2 具有与以前相同的 alpha 值。我确定我的 sharedPrefs 有问题,但我不知道是什么问题。

我是 java 的新手。所以我希望你能帮我解决这个问题:)。

感谢您的帮助!

public class MainActivity extends AppCompatActivity {

Button button, button2;
Boolean click;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);

    click = false;

    final SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefName", Context.MODE_PRIVATE);
    click= sharedPreferences.getBoolean("lockedState", true);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            click = true;
            SharedPreferences.Editor editor= sharedPreferences.edit();
            editor.putBoolean("lockedState", click);
            editor.apply();

            button2.setAlpha(0.25f);

        }
    });


}

}

【问题讨论】:

    标签: android sharedpreferences savestate


    【解决方案1】:

    onCreate下面这个click= sharedPreferences.getBoolean("lockedState", false);

    添加这些行:

    if(click)
       button2.setAlpha(0.25f);
    else
       button2.setAlpha(1f);
    

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2020-08-12
      • 1970-01-01
      相关资源
      最近更新 更多