如何将 ListPreferences 初始化为它的一个值

我试图将 defaultValue 设置为 ListPreferences 项。

下面是我的 ferences ence.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>

这两个数组:

<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>

当我进入首选项活动时,ListPreferences 的任何项都没有被选中。我尝试在“ android: defaultValue”fied 中设置类似1的 int 值,以选择“10 minutes”,但是它不起作用。

<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>

知道吗?

43258 次浏览

您需要指定 价值。因此,要获得默认选择的第一个条目,请在示例中指定 defaultValue="300"

碰巧遇到了同样的情况。指定一致的默认值。但是图像上没有被选中。我清除了申请数据。然后就像预期的那样奏效了。 因此,在开发时添加新的 XxxPreferences 项时,clear 可能很有用。

如果它是一个有效的值从列表中,然后重新安装应用程序。它将工作。

除了 Sven 的回答之外,还必须在启动活动中调用 setDefaultValue ()方法。这将设置一次所有的默认值。

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);
...
}
}