簡體   English   中英

在java中的首選項中更改true false

[英]Change true false in preferences in java

我正在嘗試使用視圖類中的Button來關閉應用程序中的聲音。 (即:靜音)當用戶按下框時,我希望代碼檢查值是否已經為真,或者使用名為“靜音”的ID設置為相反。 我想我有IF部件設置,只需要輕松更改SharedPreferences從true到flase,反之亦然......

這是我正在測試的代碼框架(BEFORE):

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
if (cmute == true){                     

}
if (cmute == false){

}

我已經嘗試了解決方案的各種發現,但大多數都太復雜了我認為這個簡單的需求..

這是我的返工后發布的建議:

if (cmute == false){


                    Editor editor = getPrefs.edit();
                    editor.putBoolean("mute", true);
                    editor.commit();
                    Editor editor2 = getPrefs.edit();
                    editor.putBoolean("notice", true);
                    editor.commit();



                }
                if (cmute == true){

                    Editor editor = getPrefs.edit();
                    editor.putBoolean("mute", false);
                    editor.commit();
                    Editor editor2 = getPrefs.edit();
                    editor.putBoolean("notice", false);
                    editor.commit();

                }

這可以通過Editor界面實現:

用於修改SharedPreferences對象中的值的接口。 您在編輯器中進行的所有更改都是批處理的,在您調用commit()或apply()之前不會將其復制回原始SharedPreferences

這對你有用:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
Editor editor = getPrefs.edit();
editor.putBoolean("mute", !cmute);
editor.commit();

評論你的建議后的版本:有沒有必要建立一個editor2 ,你甚至不使用它,你引用editor在隨后的行。 也不需要兩次調用commit。 並通過使用not運算符! 正如platzhirsch已經建議的那樣,你不需要if(cmute...

Editor editor = getPrefs.edit(); 
editor.putBoolean("mute", !cmute);
editor.putBoolean("notice", !cmute); 
editor.commit(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM