简体   繁体   中英

MultiSelectListPreference keeps old values. Is it a bug and what can be done?

If the array of choices for MultiSelectListPreference is changed, the previous stored selections in preferences can't be removed by the user.


I wrote a MultiSelectListPreference in xml as follows and used it in a PreferenceFragmentCompat:

<PreferenceCategory app:title="experiment">
    <MultiSelectListPreference
        app:key="experiment"
        app:entries="@array/abc"
        app:entryValues="@array/abc"
        app:title="my values test"
        />
</PreferenceCategory>

And the array is

<array name="abc">
    <item>a</item>
    <item>b</item>
    <item>c</item>
</array>

When in the UI selecting all choices, the result in preferences file is

<set name="experiment">
    <string>a</string>
    <string>b</string>
    <string>c</string>
</set>

Now changing the array to be

<array name="abc">
    <item>A</item>
    <item>B</item>
    <item>C</item>
</array>

and going to preferences UI again. The user sees only the new choices, and if selecting all choices the resulting preferences file is

<set name="experiment">
    <string>a</string>
    <string>A</string>
    <string>b</string>
    <string>B</string>
    <string>c</string>
    <string>C</string>
</set>

And if deselecting all choices the result is again

<set name="experiment">
    <string>a</string>
    <string>b</string>
    <string>c</string>
</set>

The user has no way to clear the old selected values.

(In my real case, the arrays are set on runtime and made from phone contacts, so they can change when contacts change.)

It looks to me like a bug. I would expect that after the user changes selections, the saved preferences would contain only choices the user sees.

My question, is it a bug, and what workaround can be done?

I did mange to make a workaround. However I would be happy for other workarounds and also having another opinion on seeing this as a bug.

Basically my workaround is to add to the arrays the existing saved values which are not in the new arrays. Then the user can uncheck them (or keep them). If the user unchecks the old values, they will not appear next time.

In override of PreferenceFragmentCompat: onCreatePreferences

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val oldValues = sharedPreferences.getStringSet("experiment",  emptySet<String>())
if (oldValues != null) {
   val onlyOldValues = oldValues.toMutableSet()
   onlyOldValues.removeAll(entryValues.toSet())
   entryValues += onlyOldValues
   entries += onlyOldValues
}

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