Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class KPreference<T>(val context:Context, val name:String, private val default:T, val listener:OnPreferenceValueChanged<Any>? = null) : ReadWriteProperty<Any?, T> {
- private val TAG = "KPreference"
- val prefs by lazy {
- context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).apply {
- registerOnSharedPreferenceChangeListener({ sharedPreferences, key ->
- val listeners = Maps[name]
- if (listeners!= null && listeners.isNotEmpty()) {
- listeners.forEach { it.onChanged(name, getValueFromPreference(sharedPreferences, name, default) as Any) }
- }
- })
- }
- }
- init {
- if (listener != null) {
- if (Maps.containsKey(name)) {
- val listeners = Maps[name]
- if (listeners != null && listeners.isNotEmpty()) {
- listeners.add(listener)
- } else {
- val newListeners = ArrayList<OnPreferenceValueChanged<Any>>()
- newListeners.add(listener)
- Maps.put(name, newListeners)
- }
- } else {
- val newListeners = ArrayList<OnPreferenceValueChanged<Any>>()
- newListeners.add(listener)
- Maps.put(name, newListeners)
- }
- }
- }
- companion object {
- val PREF_NAME: String = "default"
- val Maps = HashMap<String, MutableList<OnPreferenceValueChanged<Any>>>()
- }
- override fun getValue(thisRef: Any?, property: KProperty<*>): T {
- return getPreferenceValue(name, default)
- }
- override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
- putPreferenceValue(name, value)
- }
- @Suppress("UNCHECKED_CAST")
- private fun <T> getPreferenceValue(name: String, default: T): T = with(prefs) {
- val res: Any = when (default) {
- is Long -> getLong(name, default)
- is String -> getString(name, default)
- is Int -> getInt(name, default)
- is Boolean -> getBoolean(name, default)
- is Float -> getFloat(name, default)
- else -> throw IllegalArgumentException("This type can be saved into Preferences")
- }
- return res as T
- }
- @Suppress("UNCHECKED_CAST")
- @SuppressLint("CommitPrefEdits")
- private fun <U> putPreferenceValue(name: String, value: U) = with(prefs.edit()) {
- when (value) {
- is Long -> putLong(name, value)
- is String -> putString(name, value)
- is Int -> putInt(name, value)
- is Boolean -> putBoolean(name, value)
- is Float -> putFloat(name, value)
- else -> throw IllegalArgumentException("This type can be saved into KPreferences")
- }.apply()
- }
- @Suppress("UNCHECKED_CAST")
- private fun <T> getValueFromPreference(preferences: SharedPreferences, name: String, default: T): T = with(preferences) {
- val res: Any = when (default) {
- is Long -> getLong(name, default as Long)
- is String -> getString(name, default as String)
- is Int -> getInt(name, default as Int)
- is Boolean -> getBoolean(name, default as Boolean)
- is Float -> getFloat(name, default as Float)
- else -> throw IllegalArgumentException("This type can be saved into Preferences")
- }
- return res as T
- }
- }
Add Comment
Please, Sign In to add comment