Android3.0以上版本中 SharedPreferences新增了函數
abstract Set<String> getStringSet(String key, Set<String> defValues)Retrieve a set of String values from the preferences.
同時SharedPreferences.Editor中也新增了函數
abstract SharedPreferences.Editor putStringSet(String key, Set<String> values)Set a set of String values in the preferences editor, to be written back once commit() is called.
這樣可以直接儲存一個字串集合,但是android3.0以前的版本中沒有,如何在android2.3的系統中尋找一種替代他們的方式,我們可以猜想下上面兩個函數的實現,直接看代碼:
public class SharedPreferencesHandler {final static String regularEx = "|";public static Set<String> getStringSet(SharedPreferences prefs, String key,Set<String> defValues) {String str = prefs.getString(key, "");if (!str.isEmpty()) {String[] values = str.split(regularEx);if (defValues == null) {defValues = new HashSet<String>();for (String value : values) {if (!value.isEmpty()) {defValues.add(value);}}}}return defValues;}public static SharedPreferences.Editor putStringSet(SharedPreferences.Editor ed, String key, Set<String> values) {String str = "";if (values != null | !values.isEmpty()) {Object[] objects = values.toArray();for (Object obj : objects) {str += obj.toString();str += regularEx;}ed.putString(key, str);}return ed;}}
然後使用的時候可以這樣儲存和擷取一個字串的集合:
final Set<String> snoozedIds = SharedPreferencesHandler.getStringSet(prefs, PREF_SNOOZE_IDS, new HashSet<String>());// prefs.getStringSet(PREF_SNOOZE_IDS,// new HashSet<String>());snoozedIds.add(Integer.toString(id));final SharedPreferences.Editor ed = prefs.edit();SharedPreferencesHandler.putStringSet(ed, PREF_SNOOZE_IDS,snoozedIds);// ed.putStringSet(PREF_SNOOZE_IDS, snoozedIds);ed.putLong(getAirPrefSnoozeTimeKey(id), time);ed.apply();
上面代碼親測了