0

我不确定我在这里做错了什么,希望能得到一些帮助。

在我的主要活动的 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 所以我不确定为什么它不起作用。

4

2 回答 2

0

为了使用 PreferenceManager,我发现了两个选项。第一个是我可以创建一个首选项子类,或者另一个是将它保存为字符串,然后将其转换为 Long。

这是代码:

    // set the default preferences
    PreferenceManager.setDefaultValues(context, R.xml.preferences, false);

    // get the preferences
    prefs = PreferenceManager.getDefaultSharedPreferences( context );

    // Load the values or defaults from the SharedPreferences
    msMainClockStart = Long.valueOf( prefs.getString( "Main_Clock_Minutes", "0" ) ) * 60000;

这非常有效。

于 2013-01-06T20:19:45.900 回答
0

由于您正在设置首选项

PreferenceManager.setDefaultValues(context, R.xml.preferences, false);

利用

prefs = PreferenceManager.getDefaultSharedPreferences(context)

检索首选项,而不是getPreferences()

于 2013-01-06T04:59:38.213 回答