Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to init a ListPreference to one of its values

Tags:

android

I'm trying to set a defaultValue to a ListPreference item.

Here is an sample of my preference.xml file:

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

like image 638
ol_v_er Avatar asked Sep 22 '10 14:09

ol_v_er


3 Answers

You need to specify the value. So to get the first entry selected by default specify defaultValue="300" in your example.

like image 90
sven Avatar answered Nov 18 '22 01:11

sven


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.

like image 38
coutant Avatar answered Nov 18 '22 00:11

coutant


In addition to Sven's answer, you have to call the setDefaultValues() method in the starting activity. This will set once all default values.

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);
  ...
  }
}
like image 11
Christian Schulzendorff Avatar answered Nov 18 '22 00:11

Christian Schulzendorff