如何将ListPreference初始化为其中一个值

ol_*_*_er 71 android

我正在尝试将defaultValue设置为ListPreference项.

以下是我的preference.xml文件示例:

<ListPreference android:key="notification_delay"
    android:title="@string/settings_push_delay"
    android:entries="@array/settings_push_delay_human_value"
    android:entryValues="@array/settings_push_delay_phone_value"
    android:defaultValue="????">
</ListPreference>
Run Code Online (Sandbox Code Playgroud)

两个数组:

<string-array name="settings_push_delay_human_value">
    <item>every 5 minutes</item>
    <item>every 10 minutes</item>
    <item>every 15 minutes</item>
</string-array>
<string-array
    name="settings_push_delay_phone_value">
    <item>300</item>
    <item>600</item>
    <item>900</item>
</string-array>
Run Code Online (Sandbox Code Playgroud)

当我进入首选项活动时,没有选择ListPreference的项目.我试图在"android:defaultValue"中设置一个类似于1的int值,选择"10分钟",但它不起作用.

<ListPreference android:key="notification_delay"
    android:title="@string/settings_push_delay"
    android:entries="@array/settings_push_delay_human_value"
    android:entryValues="@array/settings_push_delay_phone_value"
    android:defaultValue="1">
</ListPreference>
Run Code Online (Sandbox Code Playgroud)

任何的想法?

sve*_*ven 91

您需要指定.因此,要defaultValue="300"在示例中指定默认选择的第一个条目.

  • 小问题,我发现更清洁,将默认值抽象为字符串,然后引用它. (8认同)

小智 19

发生了同样的情况.指定一致的默认值.但是没有选择图形.我清除了应用程序数据.然后它按预期工作.因此,在添加新的XxxPreference项时,clear可能在开发时很有用.

  • 我也是.我清除了应用程序数据,一切正常! (4认同)

Chr*_*rff 11

除了Sven的答案,你还必须在起始活动中调用setDefaultValues()方法.这将设置所有默认值.

public class MainActivity extends Activity {
  protected void onCreate(final Bundle savedInstanceState) {
  // Set all default values once for this application
  // This must be done in the 'Main' first activity
  PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)