Android 如何将 ListPreference 初始化为其值之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3770100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How-to init a ListPreference to one of its values
提问by ol_v_er
I'm trying to set a defaultValue to a ListPreference item.
我正在尝试将 defaultValue 设置为 ListPreference 项目。
Here is an sample of my preference.xml file:
这是我的首选项.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>
The two arrays:
两个数组:
<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>
When i go into the preference activity, no item of the ListPreference is selected. I've tried to set an int value like 1 in the "android:defaultValue" fied to select "10 minutes" but it does not work.
当我进入首选项活动时,没有选择 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>
Any Idea?
任何的想法?
回答by sven
You need to specify the value. So to get the first entry selected by default specify defaultValue="300"
in your example.
您需要指定值。因此,要defaultValue="300"
在您的示例中指定默认选择的第一个条目。
回答by coutant
Happened to be in same situation. Specifying a consistent default value. But graphically was not selected. I cleared the application data. And then it worked as expected. So a clear may be useful at dev time when adding new XxxPreference items.
碰巧遇到同样的情况。指定一致的默认值。但没有选择图形。我清除了应用程序数据。然后它按预期工作。因此,在开发时添加新的 XxxPreference 项目时, clear 可能很有用。
回答by Christian Schulzendorff
In addition to Sven's answer, you have to call the setDefaultValues() method in the starting activity. This will set once all default values.
除了 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);
...
}
}
回答by Percy Vega
If it is a valid value from the list, then re-install the app. It will work.
如果它是列表中的有效值,则重新安装该应用程序。它会起作用。