亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

切換按鈕不適用于 SharedPreferences

切換按鈕不適用于 SharedPreferences

小唯快跑啊 2023-11-10 16:16:18
我在應用程序中使用開關按鈕來打開/關閉音樂。我正在使用 SharedPreferences 來保存切換按鈕的最后狀態。但是,當我退出應用程序并再次運行時,它始終默認為“關閉”狀態。我想始終保存用戶選擇的狀態,即使他們關閉并再次運行應用程序也是如此。這是我的代碼`public class SettingsView extends AppCompatActivity {private Switch musicSwitch;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_settings);    musicSwitch = findViewById(R.id.sLLmusicSwitch);    SharedPreferences sharedPrefs = getSharedPreferences("save", MODE_PRIVATE);    musicSwitch.setChecked(sharedPrefs.getBoolean("value", true));    switchCheckListener();}private void switchCheckListener() {    musicSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {            if (musicSwitch.isChecked()) {                // saving state of the switch button                SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();                editor.putBoolean("NameOfThingToSave", true);                editor.apply();                musicSwitch.setChecked(true);                // turn on music                Repository.getInstance().startMusic();                Toast.makeText(getApplicationContext(), "Music on", Toast.LENGTH_SHORT).show();            } else {                // saving state of the switch button                SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();                editor.putBoolean("NameOfThingToSave", false);                editor.apply();                musicSwitch.setChecked(false);                //turn off music                Repository.getInstance().pauseMusic();                Toast.makeText(getApplicationContext(), "Music off", Toast.LENGTH_SHORT).show();            }        }    });}
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

您將布爾狀態保存到 key 下的共享首選項中NameOfThingToSave,并在 onCreate 上使用 key 檢索它value。


在onCreate中適當設置鍵值:


@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_settings);

    musicSwitch = findViewById(R.id.sLLmusicSwitch);


    SharedPreferences sharedpreferences = getSharedPreferences("save",

            Context.MODE_PRIVATE);

    switchCheckListener();


    musicSwitch.setChecked(sharedpreferences.getBoolean("NameOfThingToSave", false));

}


查看完整回答
反對 回復 2023-11-10
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號