[英]Read an boolean from SharedPreferences
我想從 SettingsActivity.java 的 SwitchPrefernce/CheckBoxPreference 檢查布爾值(真/假)
MainActivity中的代碼如下:
SharedPreferences notification1, notification2, notification3;
notification1 = getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);
notification2 = getSharedPreferences("vibrate_on_create", Context.MODE_PRIVATE);
notification3 = getSharedPreferences("remove_onklick", Context.MODE_PRIVATE);
boolean playSound = notification1.getBoolean("sound_on_create", false);
boolean vibrate = notification2.getBoolean("vibrate_onklick", false);
boolean removeOnklick = notification3.getBoolean("remove_onklick", true);
以及 SettingsActivity 中的定義:
<SwitchPreference
android:title="Text 1"
android:summary="summary 1"
android:key="sound_on_create"
android:defaultValue="true"/>
<SwitchPreference
android:title="Text 2"
android:summary="summary 2"
android:key="vibrate_on_create"
android:defaultValue="true"/>
<SwitchPreference
android:title="Text 3"
android:summary="summary 3"
android:key="remove_onclick"
android:defaultValue="true"/>
如果我使用 Log.d 獲取值,這些值始終為 false false true 那么,如何獲取用戶可以在設置中設置的值?
看起來您正在使用PreferenceActivity ,因此這些值將存儲在您的應用程序的默認 SharedPreferences 中。
您當前的代碼正在查看三個單獨的首選項文件(SharedPreferences 存儲在 xml 文件中)。
不要查看值不存在的三個文件,而是從默認的 SharedPreferences 文件中獲取它們,這就是它們存在的地方:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean playSound = sharedPrefs.getBoolean("sound_on_create", false);
boolean vibrate = sharedPrefs.getBoolean("vibrate_on_create", false);
boolean removeOnklick = sharedPrefs.getBoolean("remove_onclick", true);
//testing:
Toast.makeText(this, "values: " + playSound + " " + vibrate + " " + removeOnklick, Toast.LENGTH_LONG).show();
如果您從首選項 xml 文件中保存首選項,您將需要使用:
getDefaultSharedPreferences(this)
代替
getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);
編輯:錯字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.