简体   繁体   中英

How can I get the default value of a ListPreference as defined in the XML?

How I can programmatically get the default value of a ListPreference as it have defined in the XML?

Here is the snippet of my ListPreference :

    <ListPreference
        android:defaultValue="60"
        android:entries="@array/interval_entries"
        android:entryValues="@array/interval_values"
        android:key="interval"
        android:summary="@string/interval_summary"
        android:title="@string/interval_title" />

I have been through the docs but I have not found a way to get this. Maybe I have overlooked it.

For PreferenceActivity (deprecated with Fragment), try:

ListPreference lp = (ListPreference) this.findPreference(this.getString(R.string.my_key));
lp.getValue();

Where my_key is the key value assigned to this ListPreference. Note: This value is defined in strings.xml . If you have hard-coded your key with a literal string, then substitute my_key with whichever string you've given for the android:key tag. So, in your case, the codes will be:

ListPreference lp = (ListPreference) this.findPreference("interval");
lp.getValue();

Are you trying to initially set the default value or reset it to default? Regardless have a look at:

PreferenceManager.setDefaultValues(this, R.xml.your_pref_xml, false);

and the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM