开发者

Value of a ListPreference never updates

I have a ListPreference, but when I click on an item, the value doesn't update. The getValue() returns always the same thing.

When I reclick on the ListPreference the value is unfortunately not changed.

My code :

        ListPreference lp7 = (ListPreference) findPreference("paramUpdate");
        lp7.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            ListPreference listPref = (ListPreference) preference;
        listPref.getValue();
            return false;
        }
    });

Preferences xml:

    <ListPreference android:key="paramUpdate"
            android:tit开发者_开发技巧le="@string/paramUpdate"
            android:summary="@string/paramSummaryUpdate"
            android:entries="@array/update"
            android:entryValues="@array/updateValues"
             />

Values:

<string-array name="update">
    <item>24h</item>
    <item>48h</item>
    <item>72h</item>
    <item>@string/never</item>
</string-array>

<string-array name="updateValues">
    <item>24</item>
    <item>48</item>
    <item>72</item>
    <item>0</item>
</string-array>

Where I am wrong ?


You have to return true from your onPreferenceChangeListener for the system to store the new value. See the docs for reference.


Some correctives, if you want to save preference value:

 public boolean onPreferenceChange(Preference preference, Object newValue) {
        ListPreference listPref = (ListPreference) preference;
        int index = listPref.findIndexOfValue((String) newValue);

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("my_pref", index);
        editor.apply();
        return true;
        }

Otherwise, ListPreference has updates, but saves from second time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜