我不确定我在这里做错了什么,希望能得到一些帮助。
在我的主要活动的 onCreate 方法中,我有这个:
// set the default preferences
PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
// get the preferences
prefs = getPreferences(MODE_PRIVATE);
// Load the values or defaults from the SharedPreferences
msMainClockStart = prefs.getLong( "Main_Clock_Minutes", 0 );
useShotClock = prefs.getBoolean( "Use_ShotClock", false );
msShotClockStart = prefs.getLong( "Shot_Clock_Seconds", 20000 );
tvPeriodPrefix = prefs.getString( "Period_Prefix", "P" );
valMaxPeriods = prefs.getInt( "Max_Periods", 4 );
在我的 res/xml/preferences.xml 文件中,我有以下内容
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="Main_Clock_Minutes"
android:positiveButtonText="SAVE"
android:negativeButtonText="CANCEL"
android:title="Main Clock (minutes)"
android:defaultValue="480000"
android:summary="How many minutes for the main clock."/>
<CheckBoxPreference
android:key="Use_ShotClock"
android:title="Enable Shot Clock"
android:defaultValue="true"/>
<EditTextPreference
android:key="Shot_Clock_Seconds"
android:title="Shot Clock (seconds)"
android:summary="How many seconds for the shot clock."
android:defaultValue="30000"/>
<EditTextPreference
android:key="Period_Prefix"
android:title="Period Prefix (e.g. Q, Shift, Period)"
android:defaultValue="Q"/>
<EditTextPreference
android:key="Max_Periods"
android:title="Maximum number of periods"
android:defaultValue="4"/>
由于某种原因,默认值不会从 xml 文件中读取/加载。在使用的 getLong() 方法或 getBool() 方法中输入的默认值。
有谁知道为什么?
编辑@Gunnar Karlsson
更改为后,getDefaultSharedPreferences
我在第 121 行遇到错误,即:
msMainClockStart = prefs.getLong( "Main_Clock_Minutes", 0 );
错误说“无法从 long 转换为字符串。但是 msMainClockStart 是 Long 并且 prefs.getLong() 返回 Long 所以我不确定为什么它不起作用。