MultiSelectListPreference onPreferenceChange () method for getting invalid parameters

I have an Android app with MultiSelectListPreference, and I use the method onPreferenceChange()to update the settings summary. I managed to write code that updates the summary based on the parameter newValues, but the contents of the object do not match the actual parameters selected by the user.

Here is my code:

public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (preference instanceof MultiSelectListPreference) {
        List<String> newValues = new ArrayList<>((HashSet<String>) newValue);

        MultiSelectListPreference pref = (MultiSelectListPreference) preference;
        ArrayList<String> newSummary = new ArrayList<>();

        ArrayList<CharSequence> values = new ArrayList<>(Arrays.asList(pref.getEntryValues()));

        for (int i = 0; i < newValues.size(); i++) {
            int currentIndex = findIndexOfString(values, newValues.get(i).replaceAll(" ", ""));

            String title = (currentIndex >= 0) ? pref.getEntries()[currentIndex].toString().replaceAll(" ", "") : "";

            newSummary.add(title);
        }

        pref.setSummary(TextUtils.join(", ", newSummary));
    }

    return true;
}

private static int findIndexOfString(List<CharSequence> list, String s) {
    for (int i = 0; i < list.size(); i++) {
        if (s.equals(list.get(i).toString().replaceAll(" ", ""))) {
            return i;
        }
    }

    return -1;
}
+4
source share
1 answer

This is the code that I use to set up a summary based on an newValueObject obtained from onPreferenceChange()that contains values ​​stored as a preference. (Not suitable for resume)

public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (preference instanceof MultiSelectListPreference) {
        List<String> newValues = new ArrayList<>((HashSet<String>) newValue);

        pref.setSummary(TextUtils.join(", ", getSummaryListFromValueList(newValues)));
    }

    return true;
}

private List<String> getSummaryListFromValueList(List<String> valueList) {
        String[] allSummaries = getResources().getStringArray(R.array.pref_notif);
        String[] allValues = getResources().getStringArray(R.array.pref_notif_values);

        List<String> summaryList = new ArrayList<>();
        for (int i = 0; i < allValues.length; i++) {
            for (String value : valueList) {
                if (allValues[i].equals(value)) {
                    summaryList.add(allSummaries[i]);
                }
            }
        }
        return summaryList;
    }
+1
source

Source: https://habr.com/ru/post/1683098/


All Articles