从列表首选项中获取整数或索引值

jbw*_*bww 23 android sharedpreferences

我在共享首选项中创建列表,当调用onPreferenceChanged()方法时,我想提取列表中项目的索引或某些情况下的整数值.我正在尝试构建xml数据,如下所示:

在数组中:

<string-array name="BackgroundChoices">
  <item>Dark Background</item>
  <item>Light Background</item> 
</string-array>
<array name="BackgroundValues">
  <item>1</item>
  <item>0</item> 
</array>
<string-array name="SpeedChoices">
  <item>Slow</item>
  <item>Medium</item>
  <item>Fast</item>
</string-array>    
<array name="SpeedValues">
  <item>1</item>
  <item>4</item>
  <item>16</item>
</array>
Run Code Online (Sandbox Code Playgroud)

在首选项xml文件中:

<PreferenceScreen android:key="Settings"  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:title="Settings">

<ListPreference
        android:key="keyBackground"
        android:entries="@array/BackgroundChoices"
        android:summary="Select a light or dark background." 
        android:title="Light or Dark Background"  
        android:positiveButtonText="Okay"   
        android:entryValues="@array/BackgroundValues"/>
<ListPreference 
        android:key="keySpeed" 
        android:entries="@array/SpeedChoices" 
        android:summary="Select animation speed."
        android:title="Speed" android:entryValues="@array/SpeedValues"/>
</PreferenceScreen>
Run Code Online (Sandbox Code Playgroud)

所以我的xml不起作用.我知道如何使用字符串数组而不是数组来表示值.我可以提取值字符串并从中得到我想要的但我宁愿(如果可能的话)能够得到值为int,booleans或enums的列表.这样做的习惯方法是什么?

提前致谢,

松鸦

And*_*ite 40

将首选项放入as String并使用Integer.parseInt().我认为实际上有关于你所指的限制的错误报告,但我找不到链接.根据经验,我可以告诉你只是使用Strings并拯救自己很多挫折感.

请注意其他SO用户,如果你能证明我错了,我欢迎它.


bcl*_*mer 10

安德鲁是对的,线程在这里:

它仍然被评论,但没有变化(无论如何2.3.3).

.valueOf()的Integer.parseInt()必须工作.如果valueOf()正常工作,请使用它,因为它不像parseInt()那样分配,当你需要像我一样避免使用GC时很有帮助.


Bog*_*guś 5

基于Android的ListPreference,我创建了IntListPreference.用法很简单 - 只需将此代码段放在您的首选项xml中:

<org.bogus.android.IntListPreference
    android:key="limitCacheLogs"
    android:defaultValue="20"
    android:entries="@array/pref_download_logs_count_titles"
    android:entryValues="@array/pref_download_logs_count_values"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_download_logs_count" 
/>    
Run Code Online (Sandbox Code Playgroud)

在strings.xml中

<string name="pref_download_logs_count">Number of logs per cache</string>
<string-array name="pref_download_logs_count_titles">
    <item>10</item>
    <item>20</item>
    <item>50</item>
    <item>Give me all!</item>
</string-array>
<integer-array name="pref_download_logs_count_values">
    <item>10</item>
    <item>20</item>
    <item>50</item>
    <item>-1</item>
</integer-array>
Run Code Online (Sandbox Code Playgroud)