18

是否可以在 Xml 中定义 ListPreference 并使用 getInt 从 SharedPreferences 中检索值?这是我的 XML:

<ListPreference android:key="@string/prefGestureAccuracyKey"
    android:title="@string/prefGestureAccuracyTitle" android:summary="@string/prefGestureAccuracyDesc"
    android:entries="@array/prefNumberAccuracyLabels" android:entryValues="@array/prefNumberAccuracyValues"
    android:dialogTitle="@string/prefGestureAccuracyDialog"
    android:persistent="true" android:defaultValue="2"
    android:shouldDisableView="false" />

我想通过以下方式获取值:int val = sharedPrefs.getInt(key, defaultValue)。

目前我必须使用 getString 并解析结果。

4

5 回答 5

40

我的理解是 ListPreference 只能用于字符串数组。您必须使用 getString() 并自己转换为整数。有关此问题的错误报告,请参阅http://code.google.com/p/android/issues/detail?id=2096。Google 似乎不打算扩展 ListPreference 来处理字符串以外的任何内容。

另外:您还需要将首选项存储为字符串。否则,您的首选项活动将在启动并尝试读取字符串值时崩溃。

于 2010-06-13T03:14:59.230 回答
6

我以更极端的方式做到了这一点。

我使用了 ListPreference 并使我的 entryValues 数组包含可以使用 Integer.parseInt() 转换为整数的字符串。

然后在我的 PreferencesActivity 中,我为此首选项设置了 OnPreferenceChangeListener,在 onPreferenceChange() 方法中,我为整数版本设置了不同的首选项——第二个是我在代码中实际使用的首选项。第一个仅用于用户选项。

这样我就不必每次需要查看它时都将 String 转换为 int,我只需在用户设置它时执行它。也许矫枉过正,但它确实有效:)

于 2011-09-28T18:21:25.537 回答
2

事实上,您可以在文档中阅读:

http://developer.android.com/reference/android/preference/ListPreference.html#getValue()

获取ListPreference值的方法是:

public String getValue ()

所以你得到一个字符串。这没什么大不了的,但承认整数可能更漂亮。

于 2012-05-16T21:35:55.950 回答
0

您需要创建一个 xml 资源并将默认值设置为该资源。您在 XML 文件中作为文字输入的任何内容都被视为字符串,因此当ListPreference尝试在整数数组中查找字符串时,它将引发空指针异常。

于 2012-05-04T16:42:42.007 回答
0

但对我来说,你首先得到一个字符串类型: String numStr = prefs.getString("key", "-555"); 然后:`

try {
    int yourInt =  Integer.parseInt(numStr);
    if(yourInt != -555)
    {
        //do your stuff
    }
}
catch(Exception e)
{
    ...
}

`

于 2016-08-11T00:44:58.220 回答