반응형
Reference
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences fun <T> setPreference(pref_name: String?, value: T) { PreferenceManager.getInstance()[pref_name] = value } @Suppress("UNCHECKED_CAST") fun <T> getPreference(pref_name: String?, default_value: T): T { return PreferenceManager.getInstance()[pref_name, default_value] as T } @Suppress("UNCHECKED_CAST") sealed class PreferenceManager<T>(context: Context) { object Instance: PreferenceManager<Any?>(DreamforaApplication.applicationContext()) var sp: SharedPreferences = context.getSharedPreferences("pref", MODE_PRIVATE) var editor: SharedPreferences.Editor = sp.edit() /** * Set any type of shared preferences value * @param key of the shared preferences which the caller is desire to set * @param value types: * Boolean , * StringSet, * String, * Float, * Long, * Int */ operator fun set(key: String?, value: T) { when (value) { is Boolean -> { editor.putBoolean(key, (value as Boolean)) } is Set<*> -> { editor.putStringSet(key, value as Set<String?>) } is String -> { editor.putString(key, value as String) } is Float -> { editor.putFloat(key, (value as Float)) } is Long -> { editor.putLong(key, (value as Long)) } is Int -> { editor.putInt(key, (value as Int)) } } editor.apply() } /** * Get any type of value from the shared preference * @param key the key of the shared preference * @param defaultValue types: * Boolean , * StringSet, * String, * Float, * Long, * Int * @return same type of the default value which has been passed in */ operator fun get(key: String?, defaultValue: T): T? { when (defaultValue) { is Boolean -> { val ret = sp.getBoolean(key, (defaultValue as Boolean)) return ret as T } is Collection<*> -> { val result = sp.getStringSet(key, HashSet()) return result as T? } is String -> { val ret = sp.getString(key, defaultValue as String) return ret as T? } is Float -> { val result = sp.getFloat(key, (defaultValue as Float)) return result as T } is Long -> { val result = sp.getLong(key, (defaultValue as Long)) return result as T } is Int -> { val result = sp.getInt(key, (defaultValue as Int)) return result as T } else -> return null } } companion object { fun getInstance() = Instance } } | cs |
반응형